English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Implementar un generador de códigos QR con imágenes integradas usando Zxing

La implementación de generador de código QR integrado con imagen usando Zxing tiene cierta valoración de referencia,具体如下:

La idea básica es primero usar la imagen de código QR generada por zxing, luego leer la imagen, insertar el icono en ella y luego generar la imagen completa.

最近的项目中需要生成二维码,查找了几个例子综合一下,最终得到了最终的效果,二维码可以生成图片格式(jpg等)或在网页上显示,本文仅作记录,相似之处很多,敬请谅解。。。。

注意:需要Zxing包装的工具类,大致流程是读取内嵌的图片,将内容转换为二维码,将图片内嵌到二维码中,生成图片。

以下为完整代码:

import Java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;2D;
import java.awt.Image;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.RoundRectangle;2D;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
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.ErrorCorrectionLevel;
public class Zxing {
private static final int BLACK = 0xFF000000;
private static final int WHITE = 0xFFFFFFFF;
// Anchura promedio de la imagen 
 private static final int ANCHO IMAGEN = 80; 
 private static final int ALTO IMAGEN = 80; 
 private static final int MEDIDA MITAD IMAGEN = ANCHO IMAGEN / 2; 
 private static final int ANCHO MARCO = 2; 
 // Escritor de código QR 
 private static MultiFormatWriter mutiWriter = new MultiFormatWriter(); 
public static void main(String[] args) {
try {
//BitMatrix bitMatrix = multiFormatWriter.encode(contenido, BarcodeFormat.QR_CODE, 400, 400, sugerencias);
String contenido="13400000000";//El contenido del código QR
BufferedImage image = genBarcode(contenido, 400, 400, "F:\\amazed.png");
  if (!ImageIO.write(image, "jpg", new File("F:\\",2122.jpg"))) {
   lanzar nueva IOException("No se pudo escribir una imagen de formato ");
  }
          /**
           //Cambie el código anterior por el siguiente aquí, use flujo de lectura para ingresar a la página
OutputStream os = respuesta.getOutputStream();
 if (!ImageIO.write(image, "jpg", os)) {
       lanzar nueva IOException("No se pudo escribir una imagen de formato ");
      }
          **/
} catch (WriterException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-bloque de captura generado
e.printStackTrace();
}
}
private BufferedImage convertirABufferedImage(BitMatrix matriz) {
int anchura = matriz.obtenerAnchura();
int height = matrix.getHeight();
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, matrix.get(x, y) ? NEGRO : BLANCO);
}
}
return image;
}
private static BufferedImage genBarcode(String content, int width, 
     int height, String srcImagePath) throws WriterException, 
     IOException { 
   // leer la imagen de origen 
   BufferedImage scaleImage = scale(srcImagePath, IMAGE_WIDTH, 
       , 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); 
     } 
   } 
   Map<EncodeHintType, Object> hint = new HashMap<EncodeHintType, Object>(); 
   hint.put(EncodeHintType.CHARACTER_SET, "utf-8"); //código de contenido
   hint.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);//nivel de error
   hint.put(EncodeHintType.MARGIN, 1); //establecer el ancho del área de espacio en blanco del borde exterior del código QR
   // generar código QR 
   BitMatrix matrix = mutiWriter.encode(content, BarcodeFormat.QR_CODE, 
       width, height, hint); 
   // Convertir una matriz bidimensional en un array de píxeles unidimensional 
   int halfW = matrix.getWidth() / 2; 
   int halfH = matrix.getHeight() / 2; 
   int[] pixels = new int[width * height]; 
   for (int y = 0; y < matrix.getHeight(); y++) { 
     for (int x = 0; x < matrix.getWidth(); x++) { 
       // Leer la imagen 
       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[x - halfW 
             + IMAGE_HALF_WIDTH][y - halfH + IMAGE_HALF_WIDTH]; 
       }  
       // Formar un borde alrededor de la imagen 
       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 
               && 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 
               && 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 
               && x < halfW + IMAGE_HALF_WIDTH + FRAME_WIDTH 
               && y > halfH + IMAGE_HALF_WIDTH - FRAME_WIDTH && y < halfH 
               + IMAGE_HALF_WIDTH + FRAME_WIDTH)) { 
         pixels[y * width + x] = 0xfffffff; 
       } else { 
         // Aquí se puede modificar el color del código QR, se puede establecer el color del código QR y el color de fondo por separado; 
         pixels[y * width + x] = matrix.get(x, y) ? 0xff000000 
             : 0xfffffff; 
       } 
     } 
   } 
   BufferedImage image = new BufferedImage(width, height, 
       BufferedImage.TYPE_INT_RGB); 
   image.getRaster().setDataElements(0, 0, width, height, pixels); 
   return image; 
 } 
 /** 
  * Escalar la imagen original proporcionada según la altura y el ancho para generar un ícono que cumpla con los requisitos 
  * 
  * @param srcImageFile 
  *      Dirección del archivo de origen 
  * @param height 
  *      Altura objetivo 
  * @param width 
  *      Ancho objetivo 
  * @param hasFiller 
  *      Si la proporción no es correcta, ¿es necesario rellenar?: true para rellenar; false para no rellenar; 
  * @throws IOException 
  */ 
 private static BufferedImage escalar(String srcImageFile, int height, 
     int width, boolean hasFiller) throws IOException { 
   double ratio = 0.0; // 缩放比例 
   File file = new File(srcImageFile); 
   BufferedImage srcImage = ImageIO.read(file); 
   Image destImage = srcImage.getScaledInstance(width, height, 
       BufferedImage.SCALE_SMOOTH); 
   // 计算比例 
   if ((srcImage.getHeight() > height) || (srcImage.getWidth() > width)) { 
     if (srcImage.getHeight() > srcImage.getWidth()) { 
       ratio = (new Integer(height)).doubleValue() 
           / srcImage.getHeight(); 
     } else { 
       ratio = (new Integer(width)).doubleValue() 
           / srcImage.getWidth(); 
     } 
     AffineTransformOp op = new AffineTransformOp( 
         AffineTransform.getScaleInstance(ratio, ratio), null); 
     destImage = op.filter(srcImage, null); 
   } 
   if (hasFiller) {// 补白 
     BufferedImage image = new BufferedImage(width, height, 
         BufferedImage.TYPE_INT_RGB); 
     Graphics2D graphic = image.createGraphics(); 
     graphic.setColor(Color.PINK); 
     graphic.fillRect(10, 10, width, height); 
     graphic.drawRect(100, 360, width, height);
     if (width == destImage.getWidth(null)) { 
       graphic.drawImage(destImage, 0, 
           (height - destImage.getHeight(null)) / 2, 
           destImage.getWidth(null), destImage.getHeight(null), 
           Color.white, null); 
       Shape shape = new RoundRectangle2D.Float(0, (height - destImage.getHeight(null)) / 2, width, width, 20, 20);
       graphic.setStroke(new BasicStroke(5f));
       graphic.draw(shape);
     }
     else {
       graphic.drawImage(destImage, 
           (width - destImage.getWidth(null)) / 2, 0, 
           destImage.getWidth(null), destImage.getHeight(null), 
           Color.white, null);
       Shape shape = new RoundRectangle2D.Float((width - destImage.getWidth(null)) / 2, 0, width, width, 20, 20);
       graphic.setStroke(new BasicStroke(5f));
       graphic.draw(shape);
     }
     graphic.dispose(); 
     destImage = image; 
   } 
   return (BufferedImage) destImage; 
 } 
}

Esto es todo el contenido de este artículo, espero que sea útil para su aprendizaje y que todos apoyen el tutorial de grito.

Declaración: el contenido de este artículo se obtiene de la red, es propiedad del autor original, el contenido se contribuye y carga espontáneamente por los usuarios de Internet, este sitio no posee los derechos de propiedad, no ha sido editado por humanos y no asume responsabilidades legales relacionadas. Si encuentra contenido sospechoso de copyright, por favor envíe un correo electrónico a: notice#w3Aviso: al enviar un correo electrónico, por favor reemplace # con @ para denunciar y proporcionar evidencia relevante. Una vez verificada, este sitio eliminará inmediatamente el contenido sospechoso de infracción.

Te gustará