Hay muchos paquetes JAR de desarrollo para la generación de códigos QR Java. Por ejemplo, ZXing es desarrollado por Google. Aquí uso el paquete de desarrollo de Zxing para implementarlo. En muchos proyectos, necesitamos generar dinámicamente códigos QR para proporcionarlos a los usuarios, para que más personas puedan experimentar bien sus aplicaciones a través de códigos QR.
El código se publica a continuación, y se ha probado y puede copiar el código directamente para usar:
Finalmente logró resultados:
Java genera código QR
El código es el siguiente:
import java.awt.color; import java.awt.graphics2d; import java.awt.image; import java.awt.geom.affinetransform; import java.awt.image.affinetransformop; import java.awt.image.bufferedImage; import java.io.file; import java.io.io.io.io.io.ioccion; java.io.unsupportedencodingException; import java.util.hashmap; import java.util.map; import javax.imageio.imageio; import com.google.zxing.barcodeFormat; import com.google.zxing.encodeHintType; import com.google.zxing.multiformatwriter; import com.google.zxing.writeRexception; import Com.google.zxing.common.bitmatrix; import Com.google.zxing.qrcode.decoder.errection.errerection.errinte clase pública MatrixToImageWriter {private static final int image_width = 100; Private static final int Image_Height = 100; Private static final int Image_half_width = image_width / 2; Private static final int frame_width = 2; Private static multiformAtWriter mutiWriter = new MultiformAtWriter (); public static void encode (String Content, int Width, int HIED, String srcImagePath, String DestImagePath) {try {imageIO.Write (genBarCode (contenido, ancho, altura, srcImagePath), "jpg", nuevo archivo (desimagePath)); } catch (ioException e) {E.PrintStackTrace (); } catch (WriterException e) {E.PrintStackTrace (); }} Private static bufferedImage GenBarCode (contenido de cadena, intdh, int altura, string srcImagePath) arroja WriterException, ioexception {BufferedImage scaleMage = 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] = escalaMage.getRgb (i, j); }} Map <codeDeDintType, object> tint = new HashMap <codeDeDintType, object> (); hint.put (encodeHintType.character_set, "UTF-8"); hint.put (encodeHintType.error_correction, errorcorrectionLevel.h); // Generar el código QR BitMatrix Matrix = MutiWriter.Encode (content, BarcodeFormat.qr_code, ancho, altura, sugerir); // Convierta la matriz bidimensional en una matriz píxel unidimensional int Halfw = matrix.getWidth () / 2; int halfh = matrix.getheight () / 2; int [] píxeles = new int [width * altura]; for (int y = 0; y <matrix.getheight (); y ++) {for (int x = 0; x <matrix.getWidth (); x ++) {// El color en la esquina superior izquierda, ajusta el rango de color y el color de acuerdo con sus necesidades if (x> 0 && x <170 && y> 0 & y <170) {color color = nuevo color (231, 144, 56, 56); int colorInT = color.getRgb (); píxeles [y * ancho + x] = matrix.get (x, y)? ColorInt: 16777215; } // leer la imagen más if (x> halfw - image_half_width && x <halfw + image_half_width && y> halfh - image_half_width && y <halfh + image_half_width) {píxeles [y * width + x] = srcpixels [x - halfw + image_half_width Image_half_width]; } else if (((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> Halfw - Image_half_width - Frame_Width && Y <Halfh + Image_half_width + Frame_Width) || Image_half_width - frame_width && y <halfh - image_half_width + frame_width) || Image_half_width + frame_width && y> halfh + image_half_width - frame_width && y <halfh + image_half_width + frame_width)) {píxeles [y * ancho + x] = 0xfffffffff; // Forma un borde alrededor de la imagen} 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)); Color color = nuevo color (num1, num2, num3); int colorInT = color.getRgb (); // Aquí puede modificar el color del código QR, y puede formular el código QR y los colores de fondo respectivamente; píxeles [y * ancho + x] = matrix.get (x, y)? ColorInt: 16777215; // 0x00000: 0xffffff}}} bufferedImage imagen = new BufferedImage (ancho, altura, bufferedimage.type_int_rgb); image.getRaster (). setDataelements (0, 0, ancho, altura, píxeles); imagen de retorno; } Escala de Bufferedimage estática privada (String SrcImageFile, int HIED, INT Width, Boolean Hasfiller) lanza IOException {doble relación = 0.0; // escala archivo archivo = nuevo archivo (srcImageFile); BufferedImage srcImage = imageIO.read (archivo); Image Destimage = srcimage.getScaledInstance (ancho, altura, bufferedimage.scale_smooth); // Calcule la escala if ((srcimage.getheight ()> altura) || (srcImage.getWidth ()> width)) {if (srcImage.getheight ()> srcImage.getWidth ()) {ratio = (nuevo entero). } else {ratio = (nuevo entero (ancho)). DoubleValue () / srcimage.getWidth (); } Affinetransformop op = new Affinetransformop (affinetransform.getScaleInstance (relación, relación), nulo); Destimage = op.filter (srcimage, nulo); } if (Hasfiller) {// relleno bufferedimage image = new BufferedImage (ancho, altura, bufferedImage.type_int_rgb); Graphics2d Graphic = Image.CreateGraphics (); Graphic.SetColor (color.white); Graphic.FillRect (0, 0, ancho, altura); if (width == Destimage.getWidth (NULL)) Graphic.DrawImage (Destimage, 0, (altura - Destimage.Getheight (NULL) / 2, Destimage.getWidth (NULL), Destimage.Getheight (NULL), Color.White, Null); else Graphic.DrawImage (Destimage, (ancho - Destimage.getWidth (NULL)) / 2, 0, Destimage.getWidth (NULL), Destimage.getheight (NULL), Color.White, NULL); Graphic.Dispose (); Destimage = imagen; } return (BufferedImage) 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"); }}Puede consultar el tema: Código Java QR para el aprendizaje
Lo anterior se trata de este artículo, ayudándole a diseñar su propio código QR.