Existem muitos pacotes JAR de desenvolvimento para a geração Java de códigos QR. Por exemplo, o ZXing é desenvolvido pelo Google. Aqui eu uso o pacote de desenvolvimento da Zxing para implementá -lo. Em muitos projetos, precisamos gerar dinamicamente códigos QR para fornecê -los aos usuários, para que mais pessoas possam experimentar seus aplicativos através de códigos QR.
O código foi publicado abaixo e foi testado e você pode copiar o código diretamente para usar:
Finalmente alcançou resultados:
Java gera código QR
O código é o seguinte:
importar java.awt.color; importar java.awt.graphics2d; importar java.awt.image; importar java.awt.geom.affineTransform; importar java.awt.image.affineTransformOp; import java.awt.image.afufferedimage; import java.io.io.io.io.io.io.io.io.io.io.io.io.io.io.io.io.io.io.io.io.io.io.io.io.io.io.ofile.; java.io.unsupportEdEncodingException; importar java.util.hashmap; importar java.util.map; importar javax.imageio.imageio; importar com.google.zxing.barcodeFormat; importar com.google.zxing.encodehinttype; importar com.google.zxing.multiformatwriter; import com.google.zxing.writerexception; import com.google.zxing.common.bitmatrix; import.zception; classe pública MatrixToImageWriter {private estático final int image_width = 100; private estático final int image_height = 100; private estático final int image_half_width = image_width / 2; private estático final int estrutura_width = 2; MultifritWriter estático privado MutiWriter = new MultiformatWriter (); public static void Encodes (conteúdo da string, int largura, int altura, string srcimagePath, string destimagePath) {try {imageio.write (genBarcode (conteúdo, largura, altura, srcimagePath), "jpg", novo arquivo (DestimagePath)); } catch (ioexception e) {e.printStackTrace (); } catch (writerexception e) {e.printStackTrace (); }} private estático bufferImage genBarcode (conteúdo da string, int width, int altura, string srcImagePath) lança Writerexception, ioexception {bufferImage scaleImage = scale (srcimagePath, image_width, image_height, true); int [] [] srcpixels = new int [image_width] [image_height]; for (int i = 0; i <scaleImage.getwidth (); i ++) {for (int j = 0; j <scaleImage.getHeight (); j ++) {srcpixels [i] [j] = scaleImage.getRgb (i, j); }} Mapa <EncodeHIntType, objeto> Hint = new HashMap <EncodeHIntType, object> (); hint.put (codehinttype.character_set, "utf-8"); hint.put (codehinttype.error_correction, errorCorrectionLevel.h); // gerar código QR bitMatrix matrix = mutiwriter.encode (content, barcodeformat.qr_code, largura, altura, dica); // converte a matriz bidimensional em uma matriz de pixel unidimensional int halfw = matrix.getwidth () / 2; int halfh = matrix.getHeight () / 2; int [] pixels = new int [largura * altura]; para (int y = 0; y <matrix.getHeight (); y ++) {for (int x = 0; x <matrix.getwidth (); x ++) {// a cor no canto superior esquerdo, ajuste a faixa de cor e cor de acordo com suas necessidades se (x> 0 & & x <170 && y> int colorInt = color.getRgb (); pixels [y * width + x] = matrix.get (x, y)? ColorInt: 16777215; } // Leia a imagem mais if (x> halfw - image_half_width && x <halfw + image_half_width && y> halfh - image_half_width && y <halfh + image_half_width) {pixels [y * width + x] = srcpixels [xxiwwwwwwwwwwww + fixels [y * largura + x] = srcpixels [xxiwwwwwww) Image_half_width]; } else if ((x> halfw - image_half_width - ardeira_width && x <halfw - image_half_width + frame_width && y> halfh - image_half_width - estrutura_width && y <halfh + image_half_width + frame_width) IMAGE_HALF_WIDTH + FRAME_WIDTH && y > halfW - IMAGE_HALF_WIDTH - FRAME_WIDTH && y < halfH + IMAGE_HALF_WIDTH + FRAME_WIDTH) || (x > halfW - IMAGE_HALF_WIDTH - FRAME_WIDTH && x < halfW + IMAGE_HALF_WIDTH + FRAME_WIDTH && y > halfH - IMAGE_HALF_WIDTH - Frame_width && y <halfh - image_half_width + frame_width) || (x> halfw - image_half_width - frame_width && y <halfh - image_half_width + frame_width) > halfh + image_half_width - estrutura_width && y <halfh + image_half_width + frame_width)) {pixels [y * width + x] = 0xffffffffffff; // formam uma borda ao redor da imagem} else {// QR Code Color int num1 = (int) (50 - (50,0 - 13.0) / matrix.getHeight () * (y + 1)); int num2 = (int) (165 - (165,0 - 72.0) / matrix.getHeight () * (y + 1)); int num3 = (int) (162 - (162,0 - 107.0) / matrix.getheight () * (y + 1)); Cor cor = nova cor (num1, num2, num3); int colorInt = color.getRgb (); // Aqui você pode modificar a cor do código QR e formular o código QR e as cores de fundo, respectivamente; pixels [y * width + x] = matrix.get (x, y)? ColorInt: 16777215; // 0x00000: 0xffffff}}} bufferImage imagem = new bufferImage (largura, altura, bufferImage.type_int_rgb); image.getRaster (). setDataElements (0, 0, largura, altura, pixels); imagem de retorno; } Escala de Bufferimagem estática privada (String srcImageFile, int altura, int largura, boolean hasfiller) lança IoException {Ratio duplo = 0,0; // arquivo de arquivo de escala = novo arquivo (srcImageFile); BufferImage srcimage = imageio.read (arquivo); Image Destimage = srcimage.getScaledInstance (largura, altura, bufferImage.scale_smooth); // calcule a escala if ((srcimage.getHeight ()> altura) || (srcimage.getwidth ()> width)) {if (srcimage.getHeight ()> srcimage.getWidth ()) {ratio (new integger (altura). } else {ratio = (new integer (largura)). DoubleValue () / srcimage.getWidth (); } AFFINETRANSFORMOP OP = new AffineTransformOp (afineTransform.getScaleInstance (razão, razão), nulo); destimage = op.filter (srcimage, nulo); } if (hasfiller) {// preenchendo a imagem bufferImage = new bufferImage (largura, altura, bufferImage.type_int_rgb); Graphics2D Graphic = Image.CreateGraphics (); Graphic.setColor (color.white); Graphic.fillRect (0, 0, largura, altura); if (width == Destimage.getWidth (null)) Graphic.Drawimage (Destimage, 0, (altura - Destimage.getHeight (null)) / 2, destimage.getwidth (null), destimage.getheight (null), cor.white, null); else Graphic.Drawimage (Destimage, (Width - Destimage.getWidth (NULL)) / 2, 0, Destimage.getWidth (NULL), Destimage.getHeight (NULL), Color.white, NULL); Graphic.dispose (); destimage = imagem; } return (buffaredImage) Destimage; } public static void main(String[] args) throws UnsupportedEncodingException { // In turn, content (not supported in Chinese), width, length, middle icon path, storage path MatrixToImageWriter.encode("http://www.baidu.com/", 512, 512, "D://logo.png", "D: //2013-01.jpg"); }}Você pode se referir ao tópico: Java QR Code for Learning
O exposto acima é tudo sobre este artigo, ajudando você a projetar seu próprio código QR.