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. USACO Cow Frisbee Team

    洛谷 P2946 [USACO09MAR]牛飞盘队Cow Frisbee Team 洛谷传送门 JDOJ 2632: USACO 2009 Mar Silver 2.Cow Frisbee Team ...

  2. 用bitSet做百万级ip去重

    如果直接将几百万数据仍到bitset,内存是否够用?实际测试,600万ip放到一个bitSet中,jvm内存会爆. 所以,就简单做了下分组,构建一个HashMap<String, BitSet& ...

  3. [Python] Python 获取中文的首字母 和 全部拼音首字母

    Python 获取中文的首字母 和 全部拼音首字母 代码如下: import pinyin def getStrAllAplha(str): return pinyin.get_initial(str ...

  4. django -- ORM实现作者增删改查

    前戏 前面我们已经实现了出版社的增删改查,书的增删改查,书和出版社的对应关系.现在来写一下作者的增删改查和书的对应关系,那书和作者有什么关系呢?一个作者可以写多本书,一本书可以有多个作者,所以书和作者 ...

  5. Softmax与Sigmoid函数的联系

    译自:http://willwolf.io/2017/04/19/deriving-the-softmax-from-first-principles/ 本文的原始目标是探索softmax函数与sig ...

  6. nginx 动静分离之 tomcat

    配置文件示例 server { listen ; server_name www.xxx.com; location ~* "\.(jpg|png|jepg|js|css|xml|bmp|s ...

  7. List中的ArrayList和LinkedList源码分析

    ​ List是在面试中经常会问的一点,在我们面试中知道的仅仅是List是单列集合Collection下的一个实现类, List的实现接口又有几个,一个是ArrayList,还有一个是LinkedLis ...

  8. 【技术博客】Postman接口测试教程 - 环境、附加验证、文件上传测试

    Postman接口测试教程 - 环境.附加验证.文件上传测试 v1.0 作者:ZBW 前言 继利用Postman和Jmeter进行接口性能测试之后,我们发现Postman作为一款入门容易的工具,其内置 ...

  9. 【技术博客】移动端的点击事件与Sticky Hover问题

    目录 移动端的点击事件与Sticky Hover问题 TL;DR 前言 问题描述 背景 实现方式 问题 关于移动端浏览器的点击事件 初次发现问题后各种解决尝试:从点击事件本身下手 cursor: po ...

  10. libevent笔记3:evbuffer

    evbuffer 之前提到bufferevent结构体提供两个缓存区用来为读写提供缓存,并自动进行IO操作.这两个缓存区是使用Libevent中的evbuffer实现的,同样,Libevent中也提供 ...