URL转二维码,图片

一、使用到的jar包


     com.google.zxing
     core
     3.3.3

二、.Java代码

  • 1.将URL生成二维码
//将URL生成二维码
public BufferedImage getQcCode(String URL) {
        BufferedImage image = null;
        try {
            Map hints = new HashMap<>();
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            BitMatrix bitMatrix = new MultiFormatWriter().encode(URL, BarcodeFormat.QR_CODE, 462, 462, hints);
            //将二维码转换成图片
            image = toBufferedImage(bitMatrix);
        }catch (Exception e){
            //e.printStackTrace();
        }finally {
        }
        return image;
 }
  • 2.将二维码转换成图片
    BufferedImage -java API文档
//将二维码转换成图片
private BufferedImage toBufferedImage(BitMatrix matrix){
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        int BLACK = 0xFF000000;
        int WHITE = 0xFFFFFFFF;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int i = 0;i < width; i++){
            for (int j = 0;j < height; j++){
                image.setRGB(i, j, matrix.get(i, j) ? BLACK : WHITE);
            }
        }
        return image;
 }

(若将多张图片传到前端,现在采取的是转换成base64字符串,暂时是这样处理。)

  • 3.Controller部分
    输出图片流outputStream
public void getQcCode(HttpServletResponse response) {
        logger.info("[IN]{}: ", Thread.currentThread().getStackTrace()[1].getMethodName());
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        BufferedImage image = null;
        try {
            image = XXXX.getQcCode();
            ServletOutputStream outputStream = response.getOutputStream();
            ImageIO.write(image, "jpg", outputStream);
            //此处可使用 org.apache.commons.io.IOUtils;中的IOUtils
            IOUtils.closeQuietly(out);
        }catch (Exception e){
            logger.error(e.getMessage(), e);
        }
        logger.info("[OUT]{}: ", Thread.currentThread().getStackTrace()[1].getMethodName());
    }

你可能感兴趣的:(随笔)