Zxing은 Google에서 제공하는 바코드 (One-R Code, QR Code)에 대한 구문 분석 도구입니다. QR 코드를 생성하고 분석하는 방법을 제공합니다. 이제 zxing을 사용하여 QR 코드를 생성하고 분석하기 위해 Java의 사용을 간단히 소개합니다.
1. QR 코드 생성
1.1 zxing-core.jar 패키지를 클래스 경로에 추가하십시오.
1.2 QR 코드 생성에는 MatrixtoImageWriter 클래스의 도움이 필요합니다. 이 수업은 Google에서 제공합니다. 클래스를 소스 코드에 복사 할 수 있습니다. 여기서는이 클래스의 소스 코드를 붙여 넣고 직접 사용할 수 있습니다.
import com.google.zxing.common.bitmatrix; import javax.imageio.imageio; import java.io.file; import java.io.outputStream; import java.io.ioexception; java.awt.image.bufferedimage import; 공개 최종 클래스 MatrixToImageWriter {private static final int black = 0xff000000; 개인 정적 최종 int white = 0xffffffff; private matrixtoimagewriter () {} public static bufferedimage tobufferedimage (bitmatrix matrix) {int width = matrix.getWidth (); int height = matrix.getheight (); BufferedImage image = 새로운 BufferedImage (너비, 높이, BufferedImage.type_int_rgb); for (int x = 0; x <width; x ++) {for (int y = 0; y <height; y ++) {image.setrgb (x, y, matrix.get (x, y)? black : white); }} 반환 이미지; } public static void writeTofile (bitmatrix matrix, 문자열 형식, 파일 파일)은 ioexception {bufferedImage image = tobufferedImage (matrix); if (! imageio.write (image, format, file)) {trash new ioException ( "" + format + "형식의 이미지를" + 파일에 쓸 수 없음); }} public static void writeToStream (bitmatrix matrix, String format, outputStream 스트림)은 ioException {bufferedImage image = TobufferedImage (matrix); if (! imageio.write (image, format, stream)) {Throw New IoException ( "형식 이미지를 쓸 수 없음" + 형식); }}}1.3 QR 코드를 생성하는 구현 코드를 쓰십시오
{String content = "120605181003; http : //www.cnblogs.com/jtmjx"; 문자열 path = "C :/사용자/관리자/데스크탑/증언"; multiformatwriter multiformatwriter = new multiformatwriter (); 지도 힌트 = new Hashmap (); hints.put (encodehinttype.character_set, "utf-8"); bitmatrix bitmatrix = multiformatwriter.encode (content, barcodeformat.qr_code, 400, 400, 힌트); 파일 1 = 새 파일 (Path, "Nambeginner.jpg"); matrixtoimagewriter.writetofile (bitmatrix, "jpg", file1); } catch (예외 e) {e.printstacktrace (); }이제 실행 후 QR 코드 사진을 생성 할 수 있습니다. 매우 간단하지 않습니까? 다음으로 QR 코드를 구문 분석하는 방법을 살펴 보겠습니다.
2. QR 코드 분석
2.1 zxing-core.jar 패키지를 클래스 경로에 추가하십시오.
2.2 세대와 마찬가지로 Google에서 제공하는 보조 클래스 (Bufferedimageluminancesource)가 필요합니다. 여기에서는이 클래스의 소스 코드를 붙여 넣고 검색 문제를 저장하여 직접 복사하여 사용할 수 있습니다.
BufferedImageluminanceSource import com.google.zxing.luminancesource; import java.awt.graphics2d; java.awt.geom.affinetransform; java.awt.image.bufferedimage import; 공개 최종 클래스 BufferedImageluminancesource는 Luminancesource {Private Final BufferedImage 이미지; 개인 최종 INT 왼쪽; 개인 최종 INT 탑; public bufferedimageluminancesource (bufferedImage image) {this (image, 0, 0, image.getWidth (), image.getheight ()); } public bufferedimageluminancesource (bufferedImage 이미지, int 왼쪽, int 상단, int 너비, int 높이) {슈퍼 (너비, 높이); int sourceWidth = image.getWidth (); int sourceHeight = image.getheight (); if (왼쪽 + 너비> sourcewidth || top + height> sourceHeight) {새로운 불법 불법 행위 ( "작물 사각형은 이미지 데이터에 맞지 않습니다."); } for (int y = top; y <top+height; y ++) {for (int x = left; x <왼쪽+너비; x ++) {if ((image.getrgb (x, y) & 0xff000000) == 0) {im // = white}}} this.image = new bufferedImage (sourceWidth, sourceHeight, bufferedImage.type_byte_gray); this.image.getGraphics (). DrawImage (image, 0, 0, null); this.left = 왼쪽; this.top = 상단; } @override public byte [] getrow (int y, byte [] row) {if (y <0 || y> = getheight ()) {throw new new OregalArgumentException ( "요청 된 행은 이미지 외부에 있습니다 :" + y); } int width = getWidth (); if (row == null || row.length <width) {row = new Byte [width]; } image.getRaster (). getDataelements (왼쪽, 상단 + y, 너비, 1, 행); 반환 행; } @override public byte [] getmatrix () {int width = getWidth (); int height = getheight (); int 면적 = 너비 * 높이; 바이트 [] 매트릭스 = 새로운 바이트 [영역]; image.getRaster (). getDataelements (왼쪽, 상단, 너비, 높이, 행렬); 리턴 매트릭스; } @override public boolean iscropsupported () {return true; } @override public luminancesource crop (int 왼쪽, int 상단, int 너비, int 높이) {return new bufferedimageluminancesource (이미지, this.left + left, this.top +, 너비, 높이); } @override public boolean isrotatesupported () {return true; } @override public luminancesource rotateCounterclockiswise () {int sourceWidth = image.getWidth (); int sourceHeight = image.getheight (); AffineTransform 변환 = 새로운 아파니 트랜스 폼 (0.0, -1.0, 1.0, 0.0, 0.0, sourcewidth); bufferedImage rotatedImage = new bufferedImage (sourceHeight, sourceWidth, bufferedImage.type_byte_gray); Graphics2d g = rotatedImage.creategraphics (); g.DrawImage (이미지, 변환, null); g.dispose (); int width = getWidth (); 새로운 BufferedImageluminanceSource (RotatedImage, Top, SourceWidth- (왼쪽 + 너비), getheight (), 너비)를 반환합니다. }}2.3 QR 코드를 구문 분석하는 구현 코드를 쓰십시오
{multiformatreader formatreader = new Multiformatreader (); 문자열 filepath = "c : /users/administrator/desktop/testimage/test.jpg"; 파일 = 새 파일 (filepath); BufferedImage image = imageio.read (file) ;; luminancesource source = new bufferedimageluminancesource (이미지); Binarizer binarizer = 새로운 하이브리드 비나 라이저 (소스); BinaryBitMap BinaryBitMap = New BinaryBitMap (Binarizer); 지도 힌트 = new Hashmap (); hints.put (encodehinttype.character_set, "utf-8"); 결과 결과 = formatreader.decode (binarybitMap, 힌트); System.out.println ( "result ="+ result.toString ()); System.out.println ( "resultformat ="+ result.getBarcodeFormat ()); System.out.println ( "resulttext ="+ result.getText ()); } catch (예외 e) {e.printstacktrace (); }이제 실행 후 콘솔이 QR 코드의 내용을 인쇄한다는 것을 알 수 있습니다.
지금까지 Zxing은 ZXing을 사용하여 QR 코드를 생성하고 구문 분석했으며 데모가 완료되어 주로 직접 메모를 만들고 동시에 도움이 필요한 사람들에게 편리하게 만듭니다. 헤헤!
ZXing을 사용하여 QR 코드를 생성하는 Java의 위의 간단한 예는 내가 공유하는 모든 컨텐츠입니다. 나는 당신이 당신에게 참조를 줄 수 있기를 바랍니다. 그리고 당신이 wulin.com을 더 지원할 수 있기를 바랍니다.