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. Python基础之while和for

    实现ATM的输入密码重新输入的功能 while True: user_db = 'nick' pwd_db = '123' inp_user = input('username: ') inp_pwd ...

  2. USACO Protecting the Flowers

    洛谷 P2878 [USACO07JAN]保护花朵Protecting the Flowers 洛谷传送门 JDOJ 1009: 护花 JDOJ传送门 Description FJ出去砍木材去了,把N ...

  3. Windbg Register(寄存器)窗口的使用

    寄存器是位于在 CPU 的小易失性内存单位. 许多寄存器专用于特定用途,并可用于用户模式应用程序使用的其他寄存器. 基于 x86 和基于 x64 的处理器在有可用的寄存器的不同集合. 如何打开寄存器窗 ...

  4. Windows彻底卸载VMWare虚拟机详细步骤

    不能卸载vmware ,原因是VMware的服务在运行中,停止服务就可以卸载了. 点击开始输入[services.msc],然后点击搜索到服务. 找到这个软件的图一的所有项,然后右键它属性. 全部设置 ...

  5. Markdown 编辑器指南

    一直觉得博客园默认的编辑器不好用,后来了解了Markdown,并且博客园也支持Markdown标记,所以写篇博客总结下. 一.认识 Markdown Markdown 是一种用来写作的轻量级「标记语言 ...

  6. Python 3.X 练习集100题 01

    有以下几个数字:1.2.3.4.5,能组成多少个互不相同且无重复数字的三位数?都是多少? 方法1: import itertools from functools import reduce lyst ...

  7. 029 ElasticSearch----全文检索技术04---基础知识详解02-查询

    1.查询 (1)基本查询 基本语法: GET /索引库名/_search { "query":{ "查询类型":{ "查询条件":" ...

  8. os-enviroment

    pip3 install PyUserInput ping 是不带协议的

  9. SpringCloud 基础

    目录 SpringCloud 基础 一.概述 二.服务发现组件 Eureka 1. 介绍 2. 搭建 Maven 父工程 3. 创建 Eureka 集群 4. 创建服务提供方集群 5. 创建服务消费方 ...

  10. ImageView基本用法

    1.background通常指的都是背景,而src指的是内容. 2.当使用src填入图片时,是按照图片大小直接填充,并不会进行拉伸. 3.scaleType缩放类型设置: fitXY:对图像的横向与纵 ...