使用zxing生成二维码,边框自定义宽度

本人语言组织能力较弱,直接上代码加注释。

1、基本方法

二维码容错率,分四个等级:H、L 、M、 Q

        ErrorCorrectionLevel level = ErrorCorrectionLevel.H;
  
        String qrName = "test.png"; //生成二维码图片名称
        String targetPath = ServletActionContext.getServletContext().getRealPath("/");  //不解释
        File target = new File(targetPath, qrName);
        if(!target.exists()){
            target.mkdirs();
        }

//生成二维码中的设置
        Hashtable hints = new Hashtable();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); //编码
        hints.put(EncodeHintType.ERROR_CORRECTION, level); //容错率
        hints.put(EncodeHintType.MARGIN, 0);  //二维码边框宽度,这里文档说设置0-4,但是设置后没有效果,不知原因,

        String content = “二维码内容”;

         int size = 200;  //二维码图片大小

        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, size, size,hints); //生成bitMatrix

        int margin = 5;  //自定义白边边框宽度

        bitMatrix = updateBit(bitMatrix, margin);  //生成新的bitMatrix

        //因为二维码生成时,白边无法控制,去掉原有的白边,再添加自定义白边后,二维码大小与size大小就存在差异了,为了让新

生成的二维码大小还是size大小,根据size重新生成图片

        BufferedImage bi =  MatrixToImageWriter.toBufferedImage(bitMatrix);
        bi = zoomInImage(bi,size,size);//根据size放大、缩小生成的二维码
        ImageIO.write(bi, "png", target); //生成二维码图片

这样生成的二维码在图片属性上跟我们设置的图片大小size是一致的。

唯一不明白的就是zxing库中生成二维码是设置白边边框不起作用,如果起作用,就不用这么麻烦了。


 2、调用的方法

因为二维码边框设置那里不起作用,不管设置多少,都会生成白边,所以根据网上的例子进行修改,自定义控制白边宽度,

该方法生成自定义白边框后的bitMatrix;

 private BitMatrix updateBit(BitMatrix matrix, int margin){
        int tempM = margin*2;
       int[] rec = matrix.getEnclosingRectangle();   //获取二维码图案的属性
            int resWidth = rec[2] + tempM;
            int resHeight = rec[3] + tempM;
            BitMatrix resMatrix = new BitMatrix(resWidth, resHeight); // 按照自定义边框生成新的BitMatrix
            resMatrix.clear();
        for(int i= margin; i < resWidth- margin; i++){   //循环,将二维码图案绘制到新的bitMatrix中
            for(int j=margin; j < resHeight-margin; j++){
                if(matrix.get(i-margin + rec[0], j-margin + rec[1])){
                    resMatrix.set(i,j);
                }
            }
        }
         return resMatrix;
    }


  /**
     * 图片放大缩小
     */
    public static BufferedImage  zoomInImage(BufferedImage  originalImage, int width, int height){
        BufferedImage newImage = new BufferedImage(width,height,originalImage.getType());
        Graphics g = newImage.getGraphics();
        g.drawImage(originalImage, 0,0,width,height,null);
        g.dispose();
        return newImage;

    }

另外二维码的几种生成方法 :

      需要引入的包,这里使用的是google的生成方法

            import java.awt.BasicStroke;
            import java.awt.Color;
            import java.awt.Graphics2D;
            import java.awt.image.BufferedImage;
            import java.io.File;
            import java.io.IOException;
            import java.io.OutputStream;
            import java.util.HashMap;
            import java.util.Map;

            import javax.imageio.ImageIO;
            import javax.servlet.http.HttpServletResponse;

            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;

             

/**
             * 二维码工具类 需要zxingcore-2.2.jar
             *
             * @author Camey
             *
             */
            public final class QRcodeKit {
                private static final int BLACK = 0xFF000000;

                private static final int WHITE = 0xFFFFFFFF;

                /**
                 * 生成二维码
                 *
                 * @param contents
                 *            文本
                 * @param path
                 *            路径
                 * @param width
                 *            宽
                 * @param height
                 *            高
                 * @return
                 */
                    public static String buildQRcode(String contents,
                        String path,
                        Integer width,
                        Integer height) {
                    MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
                    // 用于设置QR二维码参数
                    Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
                    // 设置编码方式
                    hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
                    // 设置QR二维码的纠错级别(H为最高级别)具体级别信息
                    hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
                    File file = null;
                    try {
                        BitMatrix bitMatrix = multiFormatWriter.encode(contents,
                                BarcodeFormat.QR_CODE,
                                width,
                                height,
                                hints);

                        File filepath = new File(path);
                        if (!filepath.exists()) {
                            filepath.mkdirs();
                        }
                         file = new File(path, System.currentTimeMillis() + ".jpg");
                        writeToFile(bitMatrix, "jpg", file);
                    } catch (WriterException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    return file.getPath().replace("\\", "/");
                }



               /**
                 * 生成带logo二维码
                 *
                 * @param contents
                 *            文本
                 * @param path
                 *            路径
                 * @param width
                 *            宽
                 * @param height
                 *            高
                 * @param logoPath
                 *            logoPath路径
                 * @return
                 */
                                    public static String buildQRcode(String contents,
                        String path,
                        Integer width,
                        Integer height,
                        String logoPath) {
                    MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
                    // 用于设置QR二维码参数
                    Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
                    // 设置编码方式
                    hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
                    // 设置QR二维码的纠错级别(H为最高级别)具体级别信息
                    hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
                    File file = null;
                    try {
                        BitMatrix bitMatrix = multiFormatWriter.encode(contents,
                                BarcodeFormat.QR_CODE,
                                width,
                                height,
                                hints);
                        file = new File(path, System.currentTimeMillis() + ".jpg");
                        writeToFile(bitMatrix, "jpg", file, new File(logoPath));
                    } catch (WriterException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    return file.getPath();
                }




               /**
                 * 生成二维码 输出
                 *
                 * @param contents
                 *            文本
                 * @param path
                 *            路径
                 * @param width
                 *            宽
                 * @param height
                 *            高
                 * @return
                 */
                    public static void buildQRcode(String contents,
                        Integer width,
                        Integer height,HttpServletResponse response) {
                    MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
                    // 用于设置QR二维码参数
                    Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
                    // 设置编码方式
                    hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
                    // 设置QR二维码的纠错级别(H为最高级别)具体级别信息
                    hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
                    try {
                        BitMatrix bitMatrix = multiFormatWriter.encode(contents,
                                BarcodeFormat.QR_CODE,
                                width,
                                height,
                                hints);
                        OutputStream stream=response.getOutputStream();
                        writeToStream(bitMatrix, "jpg", stream);
                        } catch (WriterException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }


               public static 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;
                }



               public static void writeToFile(BitMatrix matrix,
                        String format,
                        File file) throws IOException {
                    BufferedImage image = toBufferedImage(matrix);
                    if (!ImageIO.write(image, format, file)) {
                        throw new IOException("Could not write an image of format "
                                + format + " to " + file);
                    }
                }



               public static void writeToStream(BitMatrix matrix,
                        String format,
                        OutputStream stream) throws IOException {
                    BufferedImage image = toBufferedImage(matrix);
                    if (!ImageIO.write(image, format, stream)) {
                        throw new IOException("Could not write an image of format "
                                + format);
                    }
                }



               public static void writeToFile(BitMatrix matrix,
                        String format,
                        File file,
                        File logoImg) throws IOException {
                    BufferedImage image = toBufferedImage(matrix);
                    // 构建绘图对象
                    Graphics2D graphics2d = image.createGraphics();

                    BufferedImage logo = ImageIO.read(logoImg);
                    int width = logo.getWidth() / 4;
                    int height = logo.getHeight() / 4;

                    // 计算图片放置位置
                    int x = (image.getWidth() - width) / 2;
                    int y = (image.getHeight() - height) / 2;

                    graphics2d.drawImage(logo, x, y, width, height, null);
                    graphics2d.drawRoundRect(x, y, width, height, 15, 15);
                    graphics2d.setStroke(new BasicStroke(2));// logo默认边框宽度
                    graphics2d.setColor(Color.WHITE);// logo默认边框颜色
                    graphics2d.drawRect(x, y, width, height);
                    graphics2d.dispose();

                    if (!ImageIO.write(image, format, file)) {
                        throw new IOException("Could not write an image of format "
                                + format + " to " + file);
                    }
                }
     


               //测试
               public static void main(String[] args) {
                    QRcodeKit.buildQRcode("http://yifriend.cn/wxPay/422/16/0/79B4DE7C/userGrant.do", "D://", 500, 500);
                }
            }

猜你喜欢

转载自blog.csdn.net/qq_29807745/article/details/53332588