Using Zxing to implement the two dimensional code generator embedded images

  • 2020-05-12 02:37:10
  • OfStack

Zxing is used to realize the embedded picture of the 2d code generator, which has a definite reference value. The details are as follows:

The basic idea is to first use the 2d image generated by zxing, then read the image, insert an icon into it, and then output the entire image.

In the recent project, we need to generate 2-d code. We found several examples and made the final effect. The 2-d code can generate image format (jpg, etc.) or display on web page.

Note: for the tool class that needs Zxing packaging, the process is to read the embedded image, convert the content into 2d code, embed the image into 2d code, and draw the image.

Here's the complete code:


import Java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.RoundRectangle2D;
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;
//  Picture width 1 a  
 private static final int IMAGE_WIDTH = 80; 
 private static final int IMAGE_HEIGHT = 80; 
 private static final int IMAGE_HALF_WIDTH = IMAGE_WIDTH / 2; 
 private static final int FRAME_WIDTH = 2; 
 
 // 2 D code writer  
 private static MultiFormatWriter mutiWriter = new MultiFormatWriter(); 
public static void main(String[] args) {
try {
//BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, 400, 400,hints);
String content="13400000000";//2 The content of the dimension code 
BufferedImage image = genBarcode(content, 400, 400, "F:\\amazed.png");
  if (!ImageIO.write(image, "jpg", new File("F:\\2122.jpg"))) {
   throw new IOException("Could not write an image of format ");
  }

          /**

           // Change the above code to here and use the stream to read into the page 

OutputStream os = response.getOutputStream();

 if (!ImageIO.write(image, "jpg",os)) {

       throw new IOException("Could not write an image of format ");

      }

          **/
} catch (WriterException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

private BufferedImage toBufferedImage(BitMatrix matrix) {
int width = matrix.getWidth();
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) ? BLACK : WHITE);
}
}
return image;
}
private static BufferedImage genBarcode(String content, int width, 
     int height, String srcImagePath) throws WriterException, 
     IOException { 
   //  Read source image  
   BufferedImage 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); 
     } 
   } 
 
   Map<EncodeHintType, Object> hint = new HashMap<EncodeHintType, Object>(); 
   hint.put(EncodeHintType.CHARACTER_SET, "utf-8"); // Content encoding 
   hint.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);// Error level 
   hint.put(EncodeHintType.MARGIN, 1); // Set up the 2 The width of the blank area of the outer border of the dimension code 
   //  generate 2 D code  
   BitMatrix matrix = mutiWriter.encode(content, BarcodeFormat.QR_CODE, 
       width, height, hint); 
 
   // 2 Dimensional matrix transformation 1 Dimensional pixel array  
   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++) { 
       //  Read the pictures  
       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]; 
       }  
       //  In the picture 4 Circumferential framing  
       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 { 
         //  You can modify it here 2 The color of the dimension code can be determined separately 2 Dimension code and background color;  
         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; 
 } 
 
 /** 
  *  The incoming original image is scaled by height and width to produce the desired icon  
  * 
  * @param srcImageFile 
  *       Source file address  
  * @param height 
  *       Target height  
  * @param width 
  *       The target width  
  * @param hasFiller 
  *       Is it necessary to make up when the proportion is wrong? true As the filler ; false For no filler ; 
  * @throws IOException 
  */ 
 private static BufferedImage scale(String srcImageFile, int height, 
     int width, boolean hasFiller) throws IOException { 
   double ratio = 0.0; //  scaling  
   File file = new File(srcImageFile); 
   BufferedImage srcImage = ImageIO.read(file); 
   Image destImage = srcImage.getScaledInstance(width, height, 
       BufferedImage.SCALE_SMOOTH); 
   //  Calculate percentage  
   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) {//  padding  
     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; 
 } 
}


Related articles: