O ZXing é uma ferramenta de análise sobre códigos de barras (código One-R, código QR) fornecido pelo Google. Ele fornece métodos para gerar e analisar códigos QR. Agora, apresentarei brevemente o uso do Java para gerar e analisar códigos QR usando o ZXing.
1. Geração de código QR
1.1 Adicione o pacote zxing-core.jar ao ClassPath.
1.2 A geração do código QR requer a ajuda da classe MatrixToImageWriter. Esta classe é fornecida pelo Google. Você pode copiar a classe para o código -fonte. Aqui, colo o código -fonte desta classe e posso ser usado diretamente.
importar com.google.zxing.common.bitmatrix; importar javax.imageio.imageio; importar java.io.file; importar java.io.OutputStream; importar java.io.ioException; importar java.awt.image.bufferiMage; Classe final pública MatrixToImageWriter {private estático final int preto = 0xff000000; private estático final int branco = 0xfffffffffff; private matrixToImageWriter () {} public static bufferImage TobBufferedImage (matriz bitMatrix) {int width = matrix.getWidth (); int height = matrix.getHeight (); Imagem bufferedImage = new bufferImage (largura, altura, bufferImage.type_int_rgb); for (int x = 0; x <width; x ++) {for (int y = 0; y <altura; y ++) {image.setrgb (x, y, matrix.get (x, y)? preto: branco); }} retornar imagem; } public static void writetofile (matriz bitMatrix, formato de string, arquivo de arquivo) lança IoException {bufferEdImage imagem = TobBufferedImage (matriz); if (! imageio.write (imagem, formato, arquivo)) {lança a nova ioException ("não pudesse escrever uma imagem do formato" + formato + "para" arquivo +); }} public static void writeToStream (matriz bitMatrix, formato de string, fluxo de saída de saída) lança IoException {bufferedImage imagem = TobBufferedImage (matriz); if (! imageio.write (imagem, formato, stream)) {lança a nova ioException ("não pudesse escrever uma imagem de formato" + formato); }}}1.3 Escreva o código de implementação que gera código QR
tente {string content = "120605181003; http: //www.cnblogs.com/jtmjx"; String Path = "C:/Usuários/Administrador/Desktop/Testimage"; MultiformatWriter multInFalMatWriter = new MultiformatWriter (); Dicas de mapa = new hashmap (); Hints.put (codehinttype.character_set, "utf-8"); BitMatrix bitMatrix = multiformatwriter.encode (conteúdo, barcodeFormat.qr_code, 400, 400, dicas); Arquivo file1 = novo arquivo (caminho, "nambeginner.jpg"); MatrixToImageWriter.WritEtoFile (BitMatrix, "JPG", FILE1); } catch (Exceção e) {e.printStackTrace (); }Agora, após a execução, você pode gerar uma imagem de código QR. Não é muito simples? Em seguida, vamos dar uma olhada em como analisar o código QR
2. Análise do código QR
2.1 Adicione o pacote zxing-core.jar ao ClassPath.
2.2 Como a geração, precisamos de uma classe auxiliar (BufferImageluminancesource), que também é fornecida pelo Google. Aqui também colo o código -fonte desta classe e posso copiar e usá -lo diretamente, economizando o problema de pesquisar.
BufferImagelumumenseRce Import com.google.zxing.luminancesource; importar java.awt.graphics2d; importar java.awt.geom.affineTransform; importar java.awt.image.bufferiMage; Classe final public Final BufferImageluminâncias OURCE estende Luminancesource {private final bufferImage imagem; private final int esquerd; private final int top; public bufferImagelumumensource (imagem bufferImage) {this (imagem, 0, 0, image.getWidth (), image.getHeight ()); } public bufferImagelumumensource (imagem bufferiMage, int esquerda, int topo, int width, int altura) {super (largura, altura); int fonteswidth = image.getWidth (); int fontesHeight = image.getHeight (); if (esquerda + largura> fonte de largura || topo + altura> fonteHeight) {lança nova ilegalArgumentException ("O retângulo de cultivo não se encaixa nos dados da imagem."); } para (int y = top; y <topo+altura; y ++) {for (int x = esquerda; x <esquerda+largura; x ++) {if ((image.getRgb (x, y) e 0xffffffff) == 0) {image.setrgb (x, y, 0xfffffff); // = branco}}} this.image = new bufferImage (fonte de origem, fonteHeight, bufferImage.type_byte_gray); this.Image.getGraphics (). drawimage (imagem, 0, 0, nulo); this.left = esquerda; this.top = top; } @Override public byte [] getRow (int y, byte [] linha) {if (y <0 || y> = gethight ()) {lança novo ilegalArgumentException ("Linha solicitada está fora da imagem:" + y); } int width = getWidth (); if (linha == null || line.length <width) {linha = novo byte [width]; } image.getRaster (). getDataElements (esquerda, superior + y, largura, 1, linha); linha de retorno; } @Override public byte [] getMatrix () {int width = getWidth (); int altura = getheight (); Int área = largura * altura; byte [] matrix = novo byte [área]; image.getRaster (). getDataElements (esquerda, superior, largura, altura, matriz); Matriz de retorno; } @Override public boolean iscropsupported () {return true; } @Override luminâncias públicas Crop (int esquerda, int, int largura, int altura) {Retorne new BufferImageluminancesource (imagem, this.left + esquerda, this.top + topo, largura, altura); } @Override public boolean isrotatesupported () {return true; } @Override luminâncias públicas RotatecounterClockwise () {int fontesWidth = image.getWidth (); int fontesHeight = image.getHeight (); AffineTransform Transform = New AffineTransform (0,0, -1,0, 1,0, 0,0, 0,0, largura de fonte); BufferImage rotateImage = new bufferImage (fonte de peso, wontewidth, bufferImage.type_byte_gray); Graphics2d g = giratedImage.creategraphics (); g.Drawimage (imagem, transformação, nulo); G.Dispose (); int width = getWidth (); Retornar New BufferEdImagelumumensource (RotateImage, Top, SourceWidth - (esquerda + largura), Gethight (), Largura); }}2.3 Escreva o código de implementação que analisa o código QR
tente {multiformatreader formatReader = new MultInFalMAreader (); String filepath = "c: /users/administrator/desktop/testimage/test.jpg"; Arquivo de arquivo = novo arquivo (filepath); BufferImage imagem = imageio.read (arquivo) ;; Luminâncias fontes = new bufferImageluminâncias (imagem); BINARIZER BINARIZER = NOVO HYBRIDBINARIZER (ORIGE); Binarybitmap binarybitmap = new binarybitmap (binarizador); Dicas de mapa = new hashmap (); Hints.put (codehinttype.character_set, "utf-8"); Resultado resultado = formatReader.Decode (binarybitmap, dicas); System.out.println ("resultado ="+ resultado.toString ()); System.out.println ("resultadoFormat ="+ result.getBarcodeFormat ()); System.out.println ("resultText ="+ resultado.getText ()); } catch (Exceção e) {e.printStackTrace (); }Agora, após a execução, você pode ver que o console imprime o conteúdo do código QR.
Até agora, o ZXing usou o Zxing para gerar e analisar o código QR e a demonstração foi concluída, principalmente fazendo memorandos e, ao mesmo tempo, com conveniência para os necessitados. hehe!
O exemplo simples de Java acima usando o ZXing para gerar códigos QR é todo o conteúdo que eu compartilho com você. Espero que você possa lhe dar uma referência e espero que você possa apoiar mais o wulin.com.