1. Suporte qrcode e Zxing QR Code Generation and Analysis;
2. O QRCode gera códigos QR e suporta adicionar imagens, como segue:
pacote comum; importar java.awt.color; importar java.awt.graphics2d; importar java.awt.image; imagem java.awt.image.bufferedimage; importar java.io.file; importar java.io.ioException; import java.util.hashmap; importar jp.sourceforge.qrcode.qrcodedecoder; import jp.sourceforge.qrcode.exception.DecodingFailedException; import com.google.zxing.barcodeFormat; importar com.google.zxing.binarizer; importar com.google.zxing.binarybitmap; importar com.google.zxing.encodehinttype; import com.google.zxing.luminancesource; com.google.zxing.notfoundException; importar com.google.zxing.writerexception; importar com.google.zxing.common.bitmatrix; import com.google.zxing.common.hybridbinarizer; importar com.swetake.util.qrcode; / * * // Código QR Cor estática privada final int white = 0xffffffff; /** * <span style = "font-size: 18px; font-weight: Blod;"> Zxing Método gera código QR </span> * @param texto <a href = "javascript: void ();" Rel = "Nofollow externo"> Conteúdo do código QR </a>* @param largura QR Código largura* @param altura qr altura* @param outputpath qr geração de código e salvar caminho* @param imageType qr Generation format*/ public static void zxingCODecReate (text) Hashmap <EncodeHintType, String> (); // Defina o caractere codificado Definir seu.put (EncodeHintType.Character_Set, "UTF-8"); tente {// 1. Gerar código QR bitmatrix cody = new MultiformatWriter (). Encode (texto, barcodeFormat.qr_code, largura, altura, his); // 2. Obtenha a largura do código QR e a altura int codeWidth = code.getWidth (); int codeHeight = code.getHeight (); // 3. Coloque o código QR no fluxo buffer -bufferImage imagem = new bufferImage (CodeWidth, CodeHeight, bufferImage.type_int_rgb); for (int i = 0; i <codewidth; i ++) {for (int j = 0; j <codeHeight; j ++) {// 4. Loop para corrigir o conteúdo do código QR na imagem da imagem.SetRGB (i, j, code.get (i, j)? Preto: branco); }} Arquivo outputImage = novo arquivo (outputPath); // Se a imagem não existir, crie a imagem se (! OutputImage.exists ()) outputImage.createNewFile (); // 5. Escreva o código QR no imagem imageio.write (imagem, imageType, outputImage); } catch (writerexception e) {e.printStackTrace (); System.out.println ("Falha na geração de código QR"); } catch (ioexception e) {e.printStackTrace (); System.out.println ("Alterar a imagem do código QR falhou"); }}/** * <span style = "font-size: 18px; font-weight: Blod;"> qr Código Análise </span> * @param analisezepath qr Code Path * @return * @throws ioexception */@suppresswarnings ({"RawTypes", "não-sucked"}) Public Object public public. FormatReader do multiformatreader MultIniforme = new MultiformatReader (); Resultado do objeto = nulo; tente {arquivo file = novo arquivo (analzepath); if (! file.exists ()) {return "O código QR não existe"; } BufferImage imagem = imageio.read (arquivo); Luminâncias fontes = new luminancesourceutil (imagem); BINARIZER BINARIZER = NOVO HYBRIDBINARIZER (ORIGE); Binarybitmap binarybitmap = new binarybitmap (binarizador); Dicas de mapa = new hashmap (); Hints.put (codehinttype.character_set, "utf-8"); resultado = formatReader.Decode (binarybitmap, dicas); } catch (notfoundException e) {e.printStackTrace (); } resultado de retorno; }/*** <span style = "font-size: 18px; font-weight: Blod;"> QRCode gera código QR </span>* @param Content QR Content* @param imgpath qr geração de código* @param versão qr versão* @param isflag se gerar uma imagem de logotom imgpath, int versão, string lotopath) {try {qrcode qrcodeHandler = new Qrcode (); // Defina a taxa de decodificação de erro de código QR, L (7%) M (15%) Q (25%) H (30%). Quanto maior a taxa de decodificação de erros, menos informações podem ser armazenadas, mas menor o requisito para a clareza do código QR qrcodeHandler.setqrcodeErrorCorrect ('m'); // n representa o número, a representa o caractere az e b representa outros caracteres qrcodeHandler.setqrcodeEncodemode ('b'); // A versão 1 é uma matriz de 21*21 e, para cada 1 aumento na versão, os dois lados do código QR são aumentados em 4; Portanto, a versão 7 é uma matriz com 45*45; A versão mais alta é 40, que é uma matriz com 177*177 qrcodeHandler.setqrcodeversion (versão); // calcule o tamanho de acordo com a versão int imgSize = 67 + 12 * (versão - 1); byte [] contentBytes = content.getbytes ("gb2312"); BufferImage bufimg = new bufferImage (imgsize, imgsize, bufferImage.type_int_rgb); Graphics2d gs = bufimg.creategraphics (); gs.setbackground (cor.white); gs.clearrect (0, 0, imgsize, imgsize); // Defina a cor da imagem> GS.SetColor preto (color.black); // definido deslocamento para não definir pode causar erro de análise int pixoff = 2; // output Content> Código QR if (ContentBytes.Length> 0 && ContentBytes.Length <130) {boolean [] [] codeout = qrcodeHandler.calqrcode (contentBytes); para (int i = 0; i <codeout.length; i ++) {for (int j = 0; j <codeout.length; j ++) {if (codeout [j] [i]) {gs.fillrect (j * 3+pixoff, i * 3+pixoff, 3, 3); }}}} else {System.err.println ("qrcode Content bytes length =" + contentBytes.length + "não em [0,130]."); } /* Determine se você precisa adicionar uma imagem de logotipo* / if (lotopath! = Null) {iCon de arquivo = novo arquivo (Logopath); if (icon.exists ()) {int width_4 = imgsize / 4; int width_8 = width_4 / 2; int height_4 = imgsize / 4; int height_8 = altura_4 / 2; Imagem img = imageio.read (ícone); gs.drawimage (img, width_4 + width_8, altura_4 + altura_8, width_4, altura_4, nulo); gs.dispose (); bufimg.flush (); } else {System.out.println ("Erro: a imagem de login não existe!"); }} gs.dispose (); bufimg.flush (); // Criar arquivo de arquivo de código QR imgfile = novo arquivo (imgpath); if (! imgfile.exists ()) imgfile.createnewfile (); // Obtenha a imagem da imagem gerada string imgtype = imgpath.substring (imgpath.lastIndexof (".") + 1, imgpath.length ()); // gerar código QR qrcode Image Imageio.write (bufimg, imgtype, imgfile); } catch (Exceção e) {e.printStackTrace (); }}/*** <span style = "font-size: 18px; font-weight: Blod;"> qrcode qr Código Análise </span>* @param codepath qr Code caminho* @return Parsing Result*/public static string qrcodeanalyze (string codepath) {filegeFile = new File); BufferImage bufimg = null; String decodedData = null; tente {if (! imagefile.exists ()) retornar "o código QR não existe"; bufimg = imageio.read (imagefile); Qrcodedecoder decodificador = new qrcodedecoder (); decodedData = new String (decodificador.Decode (new ImageUtil (BUFIMG)), "GB2312"); } catch (ioexception e) {System.out.println ("Error:" + e.getMessage ()); E.PrintStackTrace (); } catch (decodingFailedException dfe) {System.out.println ("Error:" + dfe.getMessage ()); dfe.printStackTrace (); } retornar decodedData; }} 3. Último código de teste: teste do pacote; importar java.awt.image.BufferImage; importar java.io.inputStream; importar java.net.url; importar javax.imageio.imageio; importação comum.ImageUtil; importação Common.qrcodeutil; importar jp.sourceforge.qrcode.qrcodedecoder; /*** Classe de teste de geração de código QR* @Author Cloud* @Data 2016-11-21* qrcodeTest* /public class qrcodeTest {public static void main (string [] args) lança exceção { /*** QRCode QR Geration Test* Qrcodeutil.qrcodecreate ("http://blog.csdn.net/u014266877", "e: //qrcode.jpg", 15, "e: //icon.png"); *//*** QRCODE QR ANÁLISE DO Código* String qrcodeanalyze = qrcodeutil.qrcodeanalyze ("e: //qrcode.jpg"); *//*** ZxingCode QR Geração de geração de código* qrcodeutil.zxingCodecreate ("http://blog.csdn.net/u014266877", 300, 300, "e: //zxingcode.jpg", jpg "); *//*** ZXingCode QR Análise* String zxinganalyze = qrcodeutil.zxingCodeanalyze ("e: //zxingcode.jpg") .tostring (); */ System.out.println ("Sucesso"); }}