后端生成二维码(Google zixing-去白边)转化为base64图片流渲染到前端

由于业务需求,需要打印二维码,但是jq生成的二维码无法被Clodop打印,js转化为img也不兼容,所以在后端生成二维码图片,返回到前端打印。

接下来就是贴代码了
1、使用Google zixing接口生成二维码图片,这部分是参考其他文章的,就直接贴了

public class MatrixToImageWriter {
    private static final int BLACK = 0xFF000000;
    private static final int WHITE = 0xFFFFFFFF;

//    private MatrixToImageWriter() {
//    }

    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 void QrCode(String text,int width,int height,OutputStream bs) throws WriterException, IOException {
        String format = "png";// 二维码的图片格式

        Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); // 内容所使用字符集编码
        BitMatrix bitMatrix = new MultiFormatWriter().encode(text,
                BarcodeFormat.QR_CODE, width, height, hints);
        // 生成二维码
        bitMatrix=deleteWhite(bitMatrix);
//        String fileName = System.currentTimeMillis()+".png";
//        File outputFile = new File("D:/workspace/ekp/WebContent/mp/inventory/image" + File.separator + "new.png");
        MatrixToImageWriter.writeToStream(bitMatrix, format, bs);

    }

然而这里生成的二维码是有白边的,所以需要添加去白边的方法:

private static BitMatrix deleteWhite(BitMatrix matrix) {
        int[] rec = matrix.getEnclosingRectangle();
        int resWidth = rec[2] + 1;
        int resHeight = rec[3] + 1;
//        System.out.println(resHeight+"-----"+resWidth);
        BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
        resMatrix.clear();
        for (int i = 0; i < resWidth; i++) {
            for (int j = 0; j < resHeight; j++) {
                if (matrix.get(i + rec[0], j + rec[1]))
                    resMatrix.set(i, j);
            }
        }
        return resMatrix;
    }

2、后端将生成的二维码图片转为base64文件流,返回到前端,本文的图片格式为image/png

public void qrcode(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		JsonObject json=new JsonObject();
		response.setContentType("image/png");
		String text = request.getParameter("text");
		ByteArrayOutputStream bs=new ByteArrayOutputStream();
		int height = Integer.parseInt(request.getParameter("height"));
		int width = Integer.parseInt(request.getParameter("width"));
		MatrixToImageWriter matrixToImageWriter = new MatrixToImageWriter();
		matrixToImageWriter.QrCode(text, width, height,bs);

		String imagebuf= Base64.byteArrayToBase64(bs.toByteArray());
		response.getWriter().append(imagebuf);

	}

3、接下来看看前端:
html页面,使用img标签:

<img id="image" style="width: 125px;height: 125px"></img>
js代码:请求后端,渲染到页面
$.post("${LUI_ContextPath}/mp/zp/stock/mp_zp_stock_cpchu_mes/mpZpStockCpchuMes.do?", {
            "method": "qrcode",
            "text": QRCodeStr,
            "height": 200,
            "width": 200
        }, function (data) {
            console.log(data);
            // var img=JSON.parse(data);
            <%--var url = "${LUI_ContextPath}/wdi/inventory/image/"+img.filename;--%>
            var url="data:image/png;base64,"+data;
            $("#image").attr("src", url);
        });
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值