其他分享
首页 > 其他分享> > zxing生成二维码输出在页面

zxing生成二维码输出在页面

作者:互联网

jar包: core-2.3.0.jar

 String text = "https://www.csdn.net/";
            int width = 300;
            int height = 300;

            //二维码的图片格式
            String format = "gif";
            Hashtable hints = new Hashtable();
            //内容所使用编码
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            hints.put(EncodeHintType.MARGIN, 1); //设置边框 距离
            BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints);

            //生成二维码  文件流输出到页面
            writeToStream(bitMatrix, format, response.getOutputStream());

方法:

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 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) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        return image;
    }

效果:

在这里插入图片描述

标签:matrix,format,int,image,zxing,width,二维码,height,页面
来源: https://blog.csdn.net/lzq_20120119/article/details/121521239