Os códigos QR estão por toda parte, e você pode digitalizar e receberá presentes. Os códigos QR são tão populares agora. Acredito que todos não estão muito claros sobre como os códigos QR são gerados. Agora, o editor compartilhará com você o método de ajudá -lo a aprender o método de geração de código QR compartilhando este artigo.
De fato, essa função é usada principalmente usando o frasco publicado por Goggle.
1. Geração de código QR
Adicione o pacote zxing-core.jar ao ClassPath.
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.
Um código que pode gerar código QR diretamente
public void test1 () lança exceção {String Content = "www.baidu.com"; String Path = "D: //"; MultiformatWriter multiformatSwriter = new MultiformatWriter (); // Zxing é um código de barras fornecido pelo Google. Dicas de mapa = new hashmap (); Hints.put (codehinttype.character_set, "utf-8"); BitMatrix bitMatrix = multiformatwriter.encode (conteúdo, barcodeFormat.qr_code, 400, 400, dicas); // Este é o tamanho do arquivo de foto1 = novo arquivo (caminho, "my.jpg"); MatrixToImageWriter.WritEtoFile (BitMatrix, "JPG", FILE1); System.out.println ("Execução concluída"); }Quando podemos descobrir que, depois de copiar esse código, descobrimos que houve um erro relatado por um MatrixToImageWriter, por isso precisamos procurá -lo, mas publiquei o código aqui 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); }}}Agora você pode baixar o código QR gerado no diretório raiz do disco D
Análise de código QR
Como a Generation, 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); }}Código para analisar o código QR
FormatReader do multiformatreader MultIniforme = new MultiformatReader (); String filepath = "caminho da imagem"; 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 ()); tch (Exceção e) {e.printStackTrace ();Agora, assim você pode ver o conteúdo do código QR no console.
O exposto acima é o conhecimento relevante sobre como gerar códigos QR por Zxing-Core e analisá-los. Espero que seja útil para você. Se você tiver alguma dúvida, deixe -me uma mensagem e o editor responderá a você a tempo. Muito obrigado pelo seu apoio ao site wulin.com!