java二维码生成器及下载

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_43732387/article/details/101216902

java二维码生成器及下载

1、生成二维码所需要的pom依赖

<!--二维码生成器依赖-->
<dependency>
   <groupId>com.google.zxing</groupId>
   <artifactId>core</artifactId>
   <version>3.3.3</version>
   <scope>compile</scope>
</dependency>
<dependency>
   <groupId>com.google.zxing</groupId>
   <artifactId>javase</artifactId>
   <version>3.3.3</version>
   <scope>compile</scope>
</dependency>

2、前端请求可以使用ajax请求,也可以使用windows.localtion.href="请求地址";,注意:不要使用<a>标签请求,360、ie等浏览器会产生兼容性问题。


3、主要代码解析。

这是二维码生成的主要方法

public static void  dowanload((二维码所包含内容依据个人情况而定),HttpServletRequest request, HttpServletResponse response,String tacheName) throws Exception {
    //二维码中包含的信息
    String content ="......";//(二维码所包含内容依据个人情况而定)
    Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
    // 指定编码格式
    hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
    // 指定纠错级别(L--7%,M--15%,Q--25%,H--30%)
    hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
    // 编码内容,编码类型(这里指定为二维码),生成图片宽度,生成图片高度,设置参数
    BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, 400, 400, hints);
   //设置请求头
    String fileName = 图片名称;//获取文件名
    // 读取文件转换为字节数组
    OutputStream out = response.getOutputStream();
    BufferedImage image = toBufferedImage(bitMatrix);
    //将文字信息添加到二维码图片下方(这段代码如果不需要则可以去掉不影响功能)
    if (fileName != null && !fileName.equals("")) {
        //新的图片,把带二维码下面加上文字
        BufferedImage outImage = new BufferedImage(400, 445, BufferedImage.TYPE_4BYTE_ABGR);
        Graphics2D outg = outImage.createGraphics();
        //画二维码到新的面板
        outg.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
        //画文字到新的面板
        outg.setColor(Color.BLACK);
        outg.setFont(new Font("宋体",Font.BOLD,30));
        //字体、字型、字号
        int strWidth = outg.getFontMetrics().stringWidth(fileName);
        if (strWidth > 399) {
            //长度过长就截取前面部分
            outg.drawString(fileName, 0, image.getHeight() + (outImage.getHeight() - image.getHeight())/2 + 5 );
            //画文字 //长度过长就换行
            String fileName1 = fileName.substring(0, fileName.length()/2);
            String fileName2 = fileName.substring(fileName.length()/2, fileName.length());
            int strWidth1 = outg.getFontMetrics().stringWidth(fileName1);
            int strWidth2 = outg.getFontMetrics().stringWidth(fileName2);
            outg.drawString(fileName1, 200 - strWidth1/2, image.getHeight() + (outImage.getHeight() - image.getHeight())/2 + 12 );
            BufferedImage outImage2 = new BufferedImage(400, 485, BufferedImage.TYPE_4BYTE_ABGR);
            Graphics2D outg2 = outImage2.createGraphics();
            outg2.drawImage(outImage, 0, 0, outImage.getWidth(), outImage.getHeight(), null);
            outg2.setColor(Color.BLACK);
            outg2.setFont(new Font("宋体",Font.BOLD,30));
            //字体、字型、字号
            outg2.drawString(fileName2, 200 - strWidth2/2, outImage.getHeight() + (outImage2.getHeight() - outImage.getHeight())/2 + 5 );
            outg2.dispose(); outImage2.flush();
            outImage = outImage2;
        }else {
            outg.drawString(fileName, 200 - strWidth/2 , image.getHeight() + (outImage.getHeight() - image.getHeight())/2 + 12 );
        //画文字
        }
        outg.dispose();
        outImage.flush();
        image = outImage;
    }
    //设置图片的mime类型
    String mimeType = "image/png";
    String agent = request.getHeader("user-agent");
    String newfileName =DownLoadUtils.getName(agent,fileName );
    response.setContentType(mimeType);//设置下载头
    response.setHeader("content-disposition","attachment;filename="+newfileName+".png");
    image.flush();
    //转换成png格式的IO流
    ImageIO.write(image, "png",out);
    out.flush();
    out.close();
}

上面代码中所调用的 BufferedImage方法如下

/**
 * image流数据处理
 */
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;
 }

4、controller请求

@Controller
@RequestMapping("......")//个人情况所定
public class QRCodeController {

    /**
     * 下载二维码
     * @param request
     * @param response
     * @param model
     */
    @RequestMapping("......")//个人情况所定
    public void  QR_Code(HttpServletRequest request, HttpServletResponse response,Model model){
        String code=request.getParameter("code");//二维码所包含内容
        try {
            dowanload(code,request,response,flowPath.getTacheName());//调用二维码生成及下载方法
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

完成,使用以上代码是应根据自己的需求以作更改,如果您觉得满意,赞一个!

猜你喜欢

转载自blog.csdn.net/qq_43732387/article/details/101216902