SpringBoot 二维码生成base64并上传OSS的实现示例
作者:12程序猿 发布时间:2023-05-12 04:41:33
基础环境
SpringBoot、Maven
代码实现
1.添加依赖
<!--二维码生成 -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.3</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.3</version>
</dependency>
2.工具类
package com.milu.boss.common.util;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.util.HashMap;
/**
* 链接二维码生成工具
* @author qzz
*/
@Slf4j
@Component
public class QrCodeUtil {
/**
* 默认宽度
*/
private static final Integer WIDTH = 140;
/**
* 默认高度
*/
private static final Integer HEIGHT = 140;
/**
* LOGO 默认宽度
*/
private static final Integer LOGO_WIDTH = 22;
/**
* LOGO 默认高度
*/
private static final Integer LOGO_HEIGHT = 22;
/**
* 图片格式
*/
private static final String IMAGE_FORMAT = "png";
private static final String CHARSET = "utf-8";
/**
* 原生转码前面没有 data:image/png;base64 这些字段,返回给前端是无法被解析
*/
private static final String BASE64_IMAGE = "data:image/png;base64,%s";
/**
* 生成二维码,使用默认尺寸
*
* @param content 内容
* @return
*/
public String getBase64QRCode(String content) {
return getBase64Image(content, WIDTH, HEIGHT, null, null, null);
}
/**
* 生成二维码,使用默认尺寸二维码,插入默认尺寸logo
*
* @param content 内容
* @param logoUrl logo地址
* @return
*/
public String getBase64QRCode(String content, String logoUrl) {
return getBase64Image(content, WIDTH, HEIGHT, logoUrl, LOGO_WIDTH, LOGO_HEIGHT);
}
/**
* 生成二维码
*
* @param content 内容
* @param width 二维码宽度
* @param height 二维码高度
* @param logoUrl logo 在线地址
* @param logoWidth logo 宽度
* @param logoHeight logo 高度
* @return
*/
public String getBase64QRCode(String content, Integer width, Integer height, String logoUrl, Integer logoWidth, Integer logoHeight) {
return getBase64Image(content, width, height, logoUrl, logoWidth, logoHeight);
}
private String getBase64Image(String content, Integer width, Integer height, String logoUrl, Integer logoWidth, Integer logoHeight) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
BufferedImage bufferedImage = crateQRCode(content, width, height, logoUrl, logoWidth, logoHeight);
try {
ImageIO.write(bufferedImage, IMAGE_FORMAT, os);
} catch (IOException e) {
log.error("[生成二维码,错误{}]", e);
}
// 转出即可直接使用
return String.format(BASE64_IMAGE, Base64.encode(os.toByteArray()));
}
/**
* 生成二维码
*
* @param content 内容
* @param width 二维码宽度
* @param height 二维码高度
* @param logoUrl logo 在线地址
* @param logoWidth logo 宽度
* @param logoHeight logo 高度
* @return
*/
private BufferedImage crateQRCode(String content, Integer width, Integer height, String logoUrl, Integer logoWidth, Integer logoHeight) {
if (StrUtil.isNotBlank(content)) {
ServletOutputStream stream = null;
HashMap<EncodeHintType, Comparable> hints = new HashMap<>(4);
// 指定字符编码为utf-8
hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
// 指定二维码的纠错等级为中级
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
// 设置图片的边距
hints.put(EncodeHintType.MARGIN, 2);
try {
QRCodeWriter writer = new QRCodeWriter();
BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, width, height, hints);
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
bufferedImage.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
}
}
if (StrUtil.isNotBlank(logoUrl)) {
insertLogo(bufferedImage, width, height, logoUrl, logoWidth, logoHeight);
}
return bufferedImage;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.flush();
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return null;
}
/**
* 二维码插入logo
*
* @param source 二维码
* @param width 二维码宽度
* @param height 二维码高度
* @param logoUrl logo 在线地址
* @param logoWidth logo 宽度
* @param logoHeight logo 高度
* @throws Exception
*/
private void insertLogo(BufferedImage source, Integer width, Integer height, String logoUrl, Integer logoWidth, Integer logoHeight) throws Exception {
// logo 源可为 File/InputStream/URL
Image src = ImageIO.read(new URL(logoUrl));
// 插入LOGO
Graphics2D graph = source.createGraphics();
int x = (width - logoWidth) / 2;
int y = (height - logoHeight) / 2;
graph.drawImage(src, x, y, logoWidth, logoHeight, null);
Shape shape = new RoundRectangle2D.Float(x, y, logoWidth, logoHeight, 6, 6);
graph.setStroke(new BasicStroke(3f));
graph.draw(shape);
graph.dispose();
}
/**
* 获取二维码
*
* @param content 内容
* @param output 输出流
* @throws IOException
*/
public void getQRCode(String content, OutputStream output) throws IOException {
BufferedImage image = crateQRCode(content, WIDTH, HEIGHT, null, null, null);
ImageIO.write(image, IMAGE_FORMAT, output);
}
/**
* 获取二维码
*
* @param content 内容
* @param logoUrl logo资源
* @param output 输出流
* @throws Exception
*/
public void getQRCode(String content, String logoUrl, OutputStream output) throws Exception {
BufferedImage image = crateQRCode(content, WIDTH, HEIGHT, logoUrl, LOGO_WIDTH, LOGO_HEIGHT);
ImageIO.write(image, IMAGE_FORMAT, output);
}
}
3.测试生成
public static void main(String[] args) {
QrCodeUtil qrCodeUtil=new QrCodeUtil();
String content="https://www.baidu.com/";
String logoUrl="https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png";
String url =qrCodeUtil.getBase64QRCode(content, logoUrl);
System.out.println(url);
}
执行结果:Base64 字符串
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIwAAACMCAIAAAAhotZpAAACn0lEQVR42u3bQU7jMBQG4JYFtxhpWM6WA7CcO8MJuAYSiCPMCnUqWWNFGQlB/Z7tJt+vLtoqCYk/krw8zOEk0+dgCCAJJEgCSSBBEkgCCZJAgiSQBBIkgSSQIAkkaUI6JCRjf67+uCBBggQJ0rcOpud2vjIQLYM46rggQYIECVL8TkQNSsbNOXt/IEGCBAnSvpAyHkghQYIECRKkr24nu5EKCRIkSJC2iTQKuwVAFxwSJEiQtoOUMWFjhu/NFoIECRKk60DKTs9Bn3ocIEGCBAlS6kNozyZpy4NwzwIBEiRIkCDF3+RnmBDZgtHSJM0AgwQpf9pUxj5DakVKeg7bHVLLQPR5wOzTFJ6uwToK6bLRhDQvUpITJEh9kaJu5iH70Ni07VlEQIIECRKk3GIhoxl6/vjr/uX8StqHUV0SSJAgQVquW3kKFaTEouDiQy1I9bVa6+P9PbbBmlFobA3p5famvOrHsu5SqCzw/G/JujCkfkhLqvKxXO5WSPUNpCnOpIffr/W6t1rrfyFIMct8su7qFFka1Aqifl9PqT02WMci/Twelwz1crd8U7cDaQxSGfc/T4/nN293P1YF3upMKk4tNTekS67v370XJgltASnqRh2b9okxV99gnRwpZPYSpCykwClmkDrNC981UlQjMmNAs4uFlOszJEiQIEEanlFFREvhAwkSJEiQxhcOGTfkjJ8bVZi0FESQIEGCBGl8gzX7oThq+5stHCBBggRph0gZN/AZio5d/FcFJEiQIEEKLxB6TkqBBAkSJEj7Qspo/mY0l1Me9iFBggQJ0vAGa9QvR9QvUFRjFxIkSJAg5SL1bFxm/3EvuyELCRIkSJDikaRPIEESSJAEkkCCJJAEEiSBBEkgCSRIAkkgQRJIcvoLo2P+nGoPVwkAAAAASUVORK5CYII=
4.base64 转换为图片在线工具
http://tools.jb51.net/transcoding/img2base64
5.base64图片上传oss
5.1 base64图片 转 MultipartFile
package com.milu.boss.common.util;
/**
* base64转multipartfile工具类
* @author qzz
*/
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;
import java.io.*;
/**
* base64转MultipartFile
*/
public class BASE64DecodedMultipartFile implements MultipartFile {
private final byte[] imgContent;
private final String header;
/**
*
* @param imgContent
* @param header
*/
public BASE64DecodedMultipartFile(byte[] imgContent, String header) {
this.imgContent = imgContent;
this.header = header.split(";")[0];
}
@Override
public String getName() {
return System.currentTimeMillis() + Math.random() + "." + header.split("/")[1];
}
@Override
public String getOriginalFilename() {
return System.currentTimeMillis() + (int) Math.random() * 10000 + "." + header.split("/")[1];
}
@Override
public String getContentType() {
return header.split(":")[1];
}
@Override
public boolean isEmpty() {
return imgContent == null || imgContent.length == 0;
}
@Override
public long getSize() {
return imgContent.length;
}
@Override
public byte[] getBytes() throws IOException {
return imgContent;
}
@Override
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(imgContent);
}
@Override
public void transferTo(File dest) throws IOException, IllegalStateException {
new FileOutputStream(dest).write(imgContent);
}
public static MultipartFile base64ToMultipart(String base64) {
try {
String[] baseStrs = base64.split(",");
BASE64Decoder decoder = new BASE64Decoder();
byte[] b = new byte[0];
b = decoder.decodeBuffer(baseStrs[1]);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {
b[i] += 256;
}
}
return new BASE64DecodedMultipartFile(b, baseStrs[0]);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* base64 转 MultipartFile,获取对应的InputStream
* @param base64
* @return
*/
public static InputStream getQrCodeInputStream(String base64){
MultipartFile multipartFile = BASE64DecodedMultipartFile.base64ToMultipart(base64);
try {
return multipartFile.getInputStream();
} catch (IOException e) {
return null;
}
}
}
base64图片转MultipartFile :
MultipartFile multipartFile = BASE64DecodedMultipartFile.base64ToMultipart(base64);
5.2 MultipartFile 上传oss
/**
* base64 转 MultipartFile,获取对应的InputStream
* @param base64
* @return
*/
public static InputStream getQrCodeInputStream(String base64){
MultipartFile multipartFile = BASE64DecodedMultipartFile.base64ToMultipart(base64);
try {
return multipartFile.getInputStream();
} catch (IOException e) {
return null;
}
}
图片流上传oos:
/**
* 图片流上传oos
* @param fis
* @return
*/
public String uploadImageUrl(InputStream fis){
String url = "";
try {
String fileExt = "png";;
//生成新的文件名
String newfilename = "file/";
Date now = new Date();
SimpleDateFormat date = new SimpleDateFormat("yyyyMMdd");
newfilename += date.format(now) + "/";
SimpleDateFormat time = new SimpleDateFormat("HHmmssSSS");
newfilename += time.format(now);
newfilename += "_" + new Random().nextInt(1000) + "." + fileExt;
ossService.upload(newfilename, fis);
url = "配置的阿里云OSS图片地址OSS_PIC_URL" + newfilename;
}catch (Exception e) {
e.printStackTrace();
}
return url;
}
ossService.upload:
/**
* 上传文件
*/
public boolean upload(String filepath, InputStream inputstream) {
boolean result = false;
// 初始化配置参数
String OSS_ENDPOINT = "阿里云 上传oss 配置的 ENDPOINT";
String OSS_ACCESSKEYID = "阿里云 上传oss 配置的 CCESSKEYID";
String OSS_ACCESSKEYSECRET = "阿里云 上传oss 配置的 ACCESSKEYSECRET";
String OSS_BUCKET = "阿里云 上传oss 配置的 BUCKET";
OSSClient ossClient = null;
try {
if (filepath != null && !"".equals(filepath.trim())) {
// 创建ClientConfiguration实例,按照您的需要修改默认参数
ClientConfiguration conf = new ClientConfiguration();
// 开启支持CNAME选项
conf.setSupportCname(true);
ossClient = new OSSClient(OSS_ENDPOINT, OSS_ACCESSKEYID, OSS_ACCESSKEYSECRET, conf);
// 上传
ossClient.putObject(OSS_BUCKET, filepath, inputstream);
result = true;
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("文件上传异常");
} finally {
// 关闭client
ossClient.shutdown();
}
return result;
}
参考资料:https://zhuanlan.zhihu.com/p/158576491
来源:https://blog.csdn.net/qq_26383975/article/details/124818532


猜你喜欢
- 前言上一篇文章已经介绍了fluent-mybatis项目的构建,文章地址:Java Fluent Mybatis实战之构建项目与代码生成篇上
- 在java数组中,查找数组元素是比较基础的操作了,arrays类的binarySearch就是专门实现指定元素的。同时它也属于我们常说的二分
- 安装 小试记一次使用arthas排查jvm中CPU占用过高问题。这工具 * 爆了 碾压我目前使用的全部JVM工具。curl -O https:/
- 1、spring aop实现首先application-test.yml增加如下数据源的配置spring: datasource
- TypeScript简介:TypeScript是一种由微软开发的自由和开源的编程语言。它是JavaScript的一个超集,而且本质上向这个语
- 本文实例讲述了java针对电话号码正则匹配的方法。分享给大家供大家参考。具体如下:public interface RegExpConst
- 说明:基于atguigu学习笔记。在了解spring boot自动配置原理前,再来了解下两个注解@Import注解和@Conditional
- Remember me功能就是勾选"记住我"后,一次登录,后面在有效期内免登录。先看具体配置:pom文件:<dep
- package 斐波那契数;import java.util.Scanner;class 斐波那契数 { public static voi
- 一、JVM 类加载机制JVM 类加载机制分为五个部分:加载,验证,准备,解析,初始化,下面我们就分别来看一下这五个过程。1. 加载:加载是类
- java字段值为null,不返回该字段类上打注解@JsonSerialize(include = JsonSerialize.Inclusi
- 你要学会:流的概念处理字节流的类处理字符流的类Java标准输入输出文件管理类Java语言的输入输出类库1.流的概念流是指计算机各部件之间的数
- mongodb的数据插入速度是其一个亮点,同样的10000条数据,插入的速度要比Mysql和sqlserver都要快,当然这也是要看使用者怎
- private void button1_Click(object sender, EventArgs e) &nbs
- AuthenticationProvider解析首先进入到AuthenticationProvider源码中可以看到它只是个简单的接口里面也
- 前言上一节我们搭建起了服务注册中心,为各个服务提供者和消费者提供一个桥梁,这一节我们搭建一个服务提供者,注册到注册中心开源地址:https:
- 概述事务管理对于企业应用来说是至关重要的,即使出现异常情况,它也可以保证数据的一致性。Spring Framework对事务管理提供了一致的
- 实现思路制作一个用户头像选择器仿 WeGame制作一个用户头像选择Canvas为父控件所实现,展示图片使用Image,Path当作
- 在移动应用满天飞的时代,随着移动支付的盛行,很多应用中都集成了支付功能。之前的支付一直不是我负责,近期这个项目我负责订单模块少不了要做支付,
- 开篇我们还是和原来一样,讲一讲做爬虫的思路以及需要准备的知识吧,高手们请直接忽略。首先我们来缕一缕思绪,想想到底要做什么,列个简单的需求。需