pom.xml

<!--二维码-->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.0.0</version>
</dependency>
package com.ruoyi.common.utils;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ClassPathResource; import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map; /**
* @author DurantSimpson
* @desc 二维码工具类
* @create 2018-08-16 13:46
**/
public class QRCodeUtil { private static final String CHARSET = "UTF-8"; // 字符集格式 public static final String FORMAT_NAME = "png"; // 二维码图片格式 private static final int QRCODE_SIZE = 1500; // 二维码尺寸 private static final int WIDTH = 300; // LOGO宽度 private static final int HEIGHT = 300; // LOGO高度 /**
* 生成图像
*/
public static void encode(String content) {
String filePath = "D://";
String fileName = "zxing.png"; int width = 200; // 图像宽度
int height = 200; // 图像高度
String format = "png";// 图像类型
Map<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
try {
BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
BarcodeFormat.QR_CODE, width, height, hints);// 生成矩阵
Path path = FileSystems.getDefault().getPath(filePath, fileName);
MatrixToImageWriter.writeToPath(bitMatrix, format, path);// 输出图像
System.out.println("输出成功.");
} catch (Exception e) {
e.printStackTrace();
}
} /**
* 生成二维码图片并转换成base64编码
* @param content
* @return
*/
public static String encodeToBase64(String content) {
int width = 200; // 图像宽度
int height = 200; // 图像高度
Map<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
try {
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ImageIO.write(MatrixToImageWriter.toBufferedImage(bitMatrix),"png",outputStream);
String imgsrc = Base64.encodeBase64String(outputStream.toByteArray());
return "data:image/png;base64,"+imgsrc;
} catch (Exception e) {
e.printStackTrace();
}
return "";
} /**
* 解析图像
*/
public static void decode() {
String filePath = "D://zxing.png";
BufferedImage image;
try {
image = ImageIO.read(new File(filePath));
LuminanceSource source = new BufferedImageLuminanceSource(image);
Binarizer binarizer = new HybridBinarizer(source);
BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
Map<DecodeHintType, Object> hints = new HashMap<>();
hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
Result result = new MultiFormatReader().decode(binaryBitmap, hints);// 对图像进行解码
System.out.println("图片中内容:" + result.getText());
System.out.println("encode: " + result.getBarcodeFormat());
} catch (Exception e) {
e.printStackTrace();
}
} public static void main(String[] args) {
encode("现在心情有没有好点");
//decode();
} /**
* 生成二维码图片
* @param content
* @param title
* @return
* @throws Exception
*/
public static BufferedImage createImage(String content, String title) throws Exception {
Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
hints.put(EncodeHintType.MARGIN, 2); BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, hints);
int width = bitMatrix.getWidth();
int height = bitMatrix.getHeight();
int h = height;
if (StringUtils.isNotBlank(title)){
h = height + 150;
}
BufferedImage image = new BufferedImage(width, h, BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
}
}
ClassPathResource classPathResource = new ClassPathResource("static/img/logo.png");//位于resources目录下
insertImageAndTitle(image, classPathResource.getInputStream(), true, title); // 生成的二维码中添加logo
return image;
} /**
* 二维码中添加LOGO和标题
* @param source
* @param inputStream
* @param needCompress 是否压缩logo  true/false
* @param title 标题
* @throws Exception
*/
public static void insertImageAndTitle(BufferedImage source, InputStream inputStream, boolean needCompress, String title) throws Exception {
Image src = ImageIO.read(inputStream);
int width = src.getWidth(null);
int height = src.getHeight(null);
if (needCompress) { // 压缩LOGO
if (width > WIDTH) {
width = WIDTH;
}
if (height > HEIGHT) {
height = HEIGHT;
}
Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);
BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = tag.getGraphics();
g.drawImage(image, 0, 0, null); // 绘制缩小后的图
g.dispose();
src = image;
}
// 插入LOGO
Graphics2D graph = source.createGraphics();
int x = (QRCODE_SIZE - width) / 2;
int y = (QRCODE_SIZE - height) / 2;
graph.drawImage(src, x, y, width, height, null); //Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
//graph.setStroke(new BasicStroke(3f));
//graph.draw(shape);
//添加标题
if (StringUtils.isNotBlank(title)){
Font font = new Font(null, Font.BOLD, 80);
graph.setFont(font);
FontMetrics metrics = new FontMetrics(font) {};
Rectangle2D bounds = metrics.getStringBounds(title,null);
int tx = (int) ((QRCODE_SIZE - bounds.getWidth()) / 2);
graph.drawString(title,tx,QRCODE_SIZE+100);
}
graph.dispose();
} }
package com.ruoyi.project.vip.web;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.QRCodeUtil;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.vip.service.WxCardService;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream; /**
* @author DurantSimpson
* @desc 微信会员卡
* @create 2019-01-24 14:23
**/
@Controller
@RequestMapping("vip/wxCard")
public class WxCardController { @Autowired
private WxCardService service; @RequiresAuthentication
@RequestMapping
public String wxCard(){
return "vip/wxCard/wxCard";
} @RequestMapping(value = "/list")
@ResponseBody
public JSONObject list(){
return service.list();
} @RequestMapping(value = "/form")
public String form(){
return "vip/wxCard/form";
} @RequestMapping(value = "/create")
@ResponseBody
public AjaxResult create(String notice, String prerogative, String description, String remarks){
return service.create(notice, prerogative, description, remarks);
} @PostMapping( "/remove")
@ResponseBody
public AjaxResult remove(String ids) {
return service.remove(ids);
} @RequiresAuthentication
@RequestMapping(value = "/storeList")
public String storeList(String card_id, Model model){
model.addAttribute("card_id", card_id);
return "vip/wxCard/storeList";
} @RequestMapping(value = "/createStoreList")
@ResponseBody
public AjaxResult createStoreList(String card_id){
return service.createStoreList(card_id);
} @RequestMapping(value = "/storeListList")
@ResponseBody
public JSONObject storeListList(String card_id){
return service.storeListList(card_id);
} @PostMapping( "/storeListRemove")
@ResponseBody
public AjaxResult storeListRemove(String ids) {
return service.storeListRemove(ids);
} /**
* 下载单张二维码图片png格式
* @param request
* @param response
* @throws Exception
*/
@RequestMapping("/download")
public void download(HttpServletRequest request,HttpServletResponse response) throws Exception{
String id = request.getParameter("id");
Map<String,Object> map = service.getUrlById(id);
String fileName = map.get("store_name")+".png";
response.setHeader("content-disposition", "attachment;filename="+new String(fileName.getBytes("gb2312"), "ISO8859-1"));
response.setHeader("content-type", "image/png");
BufferedImage image = QRCodeUtil.createImage(map.get("url").toString(), map.get("store_name").toString());
ImageIO.write(image, QRCodeUtil.FORMAT_NAME, response.getOutputStream());
} /**
* 下载所有的二维码图片并打包成zip格式
* @param request
* @param response
* @throws Exception
*/
@RequestMapping("/downloadAll")
public void downloadAll(HttpServletRequest request, HttpServletResponse response) throws Exception{
response.setContentType("application/zip");
response.setHeader("Content-disposition","attachment; filename=list.zip"); OutputStream outputStream = response.getOutputStream();
ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream); String cardId = request.getParameter("card_id");
List<Map<String, Object>> list = service.getUrlListByCardId(cardId);
for(int i = 0; i < list.size(); i++){
BufferedImage image = QRCodeUtil.createImage(list.get(i).get("url").toString(),list.get(i).get("store_name").toString());
ZipEntry entry = new ZipEntry(list.get(i).get("store_id").toString()+list.get(i).get("store_name").toString()+"."+QRCodeUtil.FORMAT_NAME);
zipOutputStream.putNextEntry(entry);
ImageIO.write(image, QRCodeUtil.FORMAT_NAME, zipOutputStream);
zipOutputStream.flush();
}
zipOutputStream.close();
outputStream.flush();
outputStream.close();
}
}

Springboot生成二维码并下载图片png支持打包成zip的更多相关文章

  1. jquery生成二维码并实现图片下载

    1.引入jquery的两个js文件 <script src="../scripts/erweima/jquery-1.10.2.min.js"></script& ...

  2. 详细QRCode生成二维码和下载实现案例

    using System; using System.Collections.Generic; using System.Linq; using System.Web; using ThoughtWo ...

  3. js生成二维码以及插入图片

    先根据qrcode官网demo,不同属性值的变化,二维码的变化效果:https://larsjung.de/jquery-qrcode/latest/demo/ 进入demo中,审查元素查看里面引用的 ...

  4. js将网址转为二维码并下载图片

    将一个网址转为二维码, 下面可以添加文字, 还提供下载功能 利用的是 GitHub上面的qrcode.js 和canvas <!DOCTYPE html> <html> < ...

  5. vue-qriously 生成二维码并下载、cliploard复制粘贴

    xxx.vue <template> <a-modal class="dialogRecharge" title="活动链接及二维码" v-m ...

  6. java Springboot 生成 二维码 +logo

    上码,如有问题或者优化,劳请广友下方留言 1.工具类 import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHint ...

  7. SpringMVC将url生成二维码图片直接展示在页面上

    利用google的开源包zxing生成二维码 第一步:maven项目的zxing依赖 <!-- google zxing 生成二维码 --> <dependency> < ...

  8. 链接生成二维码-PHP

    原文:http://www.upwqy.com/details/20.html 链接生成二维码 首先下载phpqrcode phpqrcode.zip 我这里使用的是TP5,把下载好的类库 放入到ex ...

  9. phporjquery生成二维码

    一.php生成二维码 下载文章末尾链接中phpcode文件 include "./phpqrcode/qrlib.php"; //QRcode::png('http://www.b ...

随机推荐

  1. java的excel表格的导出与下载

    今天做一个java对excel表格的导出和下载的时候,从网络上搜寻了下载的模板,代码如下: 控制层: @RequestMapping(value = "excelOut_identifier ...

  2. [冬令营Day1 T2]sequence

    题目描述 Description 给一个长度为N的序列以及Q的询问,每次两个参数l,r,问你序列[l,r]中的最大连续和 输入描述 Input Description 一行二个正整数N,Q. 接下来一 ...

  3. JQuery校验时间大小

    常用于按时间条件(起始日-截止日)查询时,进行校验 function checkDate(){ var startTime = $('#startTime').val(); var endTime = ...

  4. 网络协议 13 - HTTPS 协议

    之前说了 HTTP 协议的各种问题,但是它还是陪伴着互联网.陪伴着我们走过了将近二十年的风风雨雨.现在有很多新的协议尝试去取代它,来解决性能.效率等问题,但它还还能靠着“多年的情分”活的滋润.然而,近 ...

  5. 网络协议 7 - UDP 协议

    网络协议五步登天路,我们一路迈过了物理层.链路层,今天终于到了传输层.从这一层开始,很多知识应该都是服务端开发必备的知识了,今天我们就一起来梳理下.     其实,讲到 UDP,就少不了 TCP.这俩 ...

  6. Python中字符串匹配函数startswith()函数

    1.函数用途含义 Python startswith() 方法用于检查字符串是否是以指定子字符串开头,如果是则返回 True,否则返回 False.如果参数 beg 和 end 指定值,则在指定范围内 ...

  7. QFileInfo().created() 警告 created is deprecated 怎么改?

    有这样一行代码操作: QFileInfo(...).created().toString(...); QtCreator提示警告: 'created' is deprecated 'created' ...

  8. 小端存储转大端存储 & 大端存储转小端存储

    1.socket编程常用的相关函数:htons.htonl.ntohs.ntohl h:host   n:network      s:string    l:long 2.基本数据类型,2字节,4字 ...

  9. concurrent(四)Condition

    参考文档:Java多线程系列--“JUC锁”06之 Condition条件:http://www.cnblogs.com/skywang12345/p/3496716.html Condition介绍 ...

  10. C#内存泄露与资源释放 经验总结

    本文链接:http://blog.csdn.net/yokeqi/article/details/41083939 C#相比其他语言,拥有强大的垃圾回收机制,但并不是这样,你就可以对内存管理放任不管, ...