/ * @param url 链接内容 * @param wh 宽高 * @param margin 边框大小 * @return */ public BufferedImage qrCode(String url,Integer wh,Integer margin) { /* * 图片的宽度和高度 */ int width = Objects.isNull(wh)?300:wh;; int height = Objects.isNull(wh)?300:wh;; // 定义二维码的参数 HashMap
hints = new HashMap
(); // 定义字符集编码格式 hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); // 纠错的等级 L > M > Q > H 纠错的能力越高可存储的越少,一般使用M hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M); // 设置图片边距 hints.put(EncodeHintType.MARGIN,margin); BufferedImage bufferedImage = null; try { // 最终生成 参数列表 (1.内容 2.格式 3.宽度 4.高度 5.二维码参数) BitMatrix bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, width, height, hints); bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix); } catch (Exception e) { new CustomException("二维码存储失败", 400); } return bufferedImage; }
BufferedImage 类型的数据下载到浏览器
public void respImageBuffer(BufferedImage img,HttpServletResponse response){ try { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ImageOutputStream imageOutput= ImageIO.createImageOutputStream(byteArrayOutputStream); ImageIO.write(img,"png",imageOutput); ByteArrayInputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); long length = imageOutput.length(); //设置response response.setContentType("application/x-msdownload"); response.setContentLength((int)length); response.setHeader("Content-Disposition","attachment;filename=ercode.jpg"); //输出流 byte[] b = new byte[1024]; ServletOutputStream outputStream = response.getOutputStream(); long count = 0; while (count < length){ int len = inputStream.read(b, 0, 1024); count+=len; outputStream.write(b,0,len); } outputStream.flush(); }catch (Exception e){ throw new CustomException("生成二维码失败",400); } }
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/217642.html原文链接:https://javaforall.net
