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. LeetCode 825. Friends Of Appropriate Ages

    原题链接在这里:https://leetcode.com/problems/friends-of-appropriate-ages/ 题目: Some people will make friend ...

  2. 研究下vc++的abort函数

    最近在调试几个问题时,发现跟abort函数有关,以前只是简单使用,现在却发现不简单,就多留意了下. 简介 abort中止当前进程并返回错误代码.异常终止一个进程.中止当前进程,返回一个错误代码.错误代 ...

  3. 什么是ES5?js中的'use strict'是什么?目的是什么?

    什么是ES5? ECMA Script5:ECMA(欧洲计算机制造联合会)的第五次改版,2009年. js中的'use strict'是什么? js的严格模式 目的: ①添加更多报错的场合,消除代码的 ...

  4. 归并排序 MergeSort

    今天第一次看懂了严奶奶的代码( ̄▽ ̄)~*,然后按照厌奶那的思路进行了一波coding,稍加调试后即可跑起来. 学习链接:排序七 归并排序.图解排序算法(四)之归并排序 merge函数:将两个有序序列 ...

  5. 第10组 Beta冲刺(2/4)

    队名:凹凸曼 组长博客 作业博客 组员实践情况 童景霖 过去两天完成了哪些任务 文字/口头描述 编写商品主界面 展示GitHub当日代码/文档签入记录 暂无代码 接下来的计划 编写购买功能 还剩下哪些 ...

  6. dockerfile 的问题 FROM alpine:3.8 temporary error (try again later)

    FROM alpine:3.8 apk add xxx安装软件 fetch http://dl-cdn.alpinelinux.org/alpine/v3.8/main/x86_64/APKINDEX ...

  7. elasticsearch 常用命令 一直红色 重启不稳定 不停的宕机

    persistent (重启后设置也会存在) or transient (整个集群重启后会消失的设置). 查看集群状态和每个indices状态.搜索到red的,没用就删除 GET /_cluster/ ...

  8. Kafka Offset Monitor页面显示空白

    下载包:https://github.com/Morningstar/kafka-offset-monitor.git 解决:jar包内\KafkaOffsetMonitor-assembly-0.2 ...

  9. pom.xml文件引入tools.jar

    最近做hbase开发时,引入相关jar包后,出现了以下错误 Missing artifact jdk.tools:jdk.tools:jar:1.8 绝对地址引用 <dependency> ...

  10. android webview 全屏100%显示图片

    这里引用 第三方类库 implementation 'org.jsoup:jsoup:1.10.2' 定义工具类 HtmlUtils import org.jsoup.Jsoup; import or ...