增加了将生成的图片从本地磁盘删除的代码

This commit is contained in:
wen 2021-09-15 11:53:31 +08:00
parent 2508b6f829
commit 0a3d6802bc
4 changed files with 76 additions and 253 deletions

View File

@ -1,144 +0,0 @@
package com.xhpc.charging.station.utils;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Hashtable;
/**
*
* @ClassName: QRCodeUtil
* @Description: 二维码生成工具类
* @author w
*
*/
public class QRCodeUtil {
private static final String CHARSET = "utf-8";
private static final String FORMAT_NAME = "PNG";
// 二维码尺寸
private static final int QRCODE_SIZE = 400;
// LOGO宽度
private static final int WIDTH = 100;
// LOGO高度
private static final int HEIGHT = 100;
private static BufferedImage createImage(String content, String imgPath,
boolean needCompress) throws Exception {
Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
hints.put(EncodeHintType.MARGIN, 1);
BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, hints);
int width = bitMatrix.getWidth();
int height = bitMatrix.getHeight();
BufferedImage image = new BufferedImage(width, height,
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);
}
}
if (imgPath == null || "".equals(imgPath)) {
return image;
}
// 插入图片
QRCodeUtil.insertImage(image, imgPath, needCompress);
return image;
}
/**
* 插入LOGO
*
* @param source
* 二维码图片
* @param imgPath
* LOGO图片地址
* @param needCompress
* 是否压缩
* @throws Exception
*/
private static void insertImage(BufferedImage source, String imgPath,
boolean needCompress) throws Exception {
File file = new File(imgPath);
if (!file.exists()) {
System.err.println(""+imgPath+" 该文件不存在!");
return;
}
Image src = ImageIO.read(new File(imgPath));
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);
graph.dispose();
}
/**
* 生成二维码(内嵌LOGO)
*
* @param content
* 内容
* @param imgPath
* LOGO地址
* @param destPath
* 存放目录
* @param needCompress
* 是否压缩LOGO
* @param fileName
* 生成的图片名称
* @throws Exception
*/
public static void encode(String content, String imgPath, String destPath,
boolean needCompress,String fileName) throws Exception {
BufferedImage image = QRCodeUtil.createImage(content, imgPath,
needCompress);
mkdirs(destPath);
// String file = new Random().nextInt(99999999)+".png";
// String file = fileName+".png";
ImageIO.write(image, FORMAT_NAME, new File(destPath+"/"+fileName));
}
/**
* 当文件夹不存在时mkdirs会自动创建多层目录区别于mkdir(mkdir如果父目录不存在则会抛出异常)
* @param destPath 存放目录
*/
public static void mkdirs(String destPath) {
File file =new File(destPath);
//当文件夹不存在时mkdirs会自动创建多层目录区别于mkdir(mkdir如果父目录不存在则会抛出异常)
if (!file.exists() && !file.isDirectory()) {
file.mkdirs();
}
}
}

View File

@ -1,92 +0,0 @@
package com.xhpc.charging.station.utils;
import cn.hutool.core.date.DateUtil;
import com.aliyun.oss.OSSClient;
import com.xhpc.charging.station.mapper.XhpcImgMapper;
import com.xhpc.common.domain.XhpcTerminal;
import org.springframework.core.env.Environment;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Properties;
public class QrImgUtils {
//生成的二维码存放位置
private static String destPath;
//获取Logo图片位置
private static String imgPath;
//进行工具初始化
static {
InputStream is = QrImgUtils.class.getClassLoader().getResourceAsStream("QrImgUtils.properties");
Properties properties = new Properties();
try {
properties.load(is);
} catch (IOException e) {
e.printStackTrace();
System.out.println("QrImgUtils无法加载配置文件");
}
destPath = properties.getProperty("destPath");
imgPath = properties.getProperty("imgPath");
}
/**
* @Author WH
* @Date 2021/9/8 15:55
* @Description upload images to Server
* @Param [xhpcTerminal, chargingPileId, environment, xhpcImgMapper]
* @Return void
* @Since version-1.0
*/
public static void uploadImg(XhpcTerminal xhpcTerminal, String chargingPileId, Environment environment, XhpcImgMapper xhpcImgMapper) {
//生成桩的二维码图片
//1.生成二维码链接内容
StringBuilder prefix = new StringBuilder("https://xhpc.scxhua.com?pNum=");
String QrContent = prefix.append(xhpcTerminal.getSerialNumber()).toString();
//2.生成图片
try {
//2.1生成指定规则的图片名
String fileName = DateUtil.format(new Date(), "yyyyMMddHHmmssSSS") + chargingPileId + ".png"; //2021090814171100766.png
//2.2生成图片
QRCodeUtil.encode(QrContent,
imgPath,
destPath,
true,
fileName
);
//3.上传图片至服务器
// 创建OSSClient实例
OSSClient ossClient = new OSSClient(environment.getProperty("oss.endpoint"), environment.getProperty("oss.access-key"), environment.getProperty("oss.secret-key"));
// 上传文件流
ossClient.putObject(environment.getProperty("oss.bucket-name"), xhpcTerminal.getPileSerialNumber() + "/" + fileName, new File(destPath + "\\" + fileName));
ossClient.shutdown();
//4.将生成的图片的文件名和对应的终端的id放入数据库xhpc_img表中
Long terminalId = xhpcTerminal.getTerminalId();
xhpcImgMapper.insert(fileName, terminalId);
//4.删除生成的二维码图片
File QrImg = new File(destPath + "\\" + fileName);
if (QrImg.exists()) {
QrImg.delete();
} else {
throw new RuntimeException("名字为" + fileName + "的二维码不存在");
}
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
}
}

View File

@ -223,4 +223,60 @@ public class ImageUtil {
return bi;
}
/**
* 快速生成完整图片但可读性不高属于一次性生成
* @param bottomFile 底图
* @param QrCode 生成的二维码图片
* @param SerialNumber 终端编码
* @throws IOException
*/
public void fastCreateImg(File bottomFile,
File QrCode,
String SerialNumber,
String StationName,
String PileNumber,
String letter,
File fullImgdestPath) throws IOException {
//载入生成的二维码图片
BufferedImage bottomImg = ImageIO.read(bottomFile);
//二维码图片存放位置
File QrCodeImgPath = QrCode;
//使用ImageIO将图片加载到内存中
BufferedImage QrCodeImg = ImageIO.read(QrCodeImgPath);
Graphics2D g2 = bottomImg.createGraphics();
g2.drawImage(QrCodeImg,10,300,380,380,null);
//提前设置文字参数防止生成的文字带有锯齿
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g2.setFont(new Font("楷体",Font.BOLD,24));
g2.setColor(Color.WHITE);
g2.drawString("终端编码:"+SerialNumber,17,255);
//在头顶设置场站名称
//在图片中居中显示文字
String realStationName = StationName; //定义文字内容
Font font=new Font("楷体",Font.PLAIN,24); //设置文字大小
g2.setFont(font); //设置到画笔
// 计算文字长度计算居中的x点坐标
FontMetrics fm = g2.getFontMetrics(font); //获取该大小字体的字体度量单位
int textWidth = fm.stringWidth(realStationName); //传入文字内容让它计算出文字内容宽度
int widthX = (400 - textWidth) / 2; //此处的400是图片的宽度用于计算出文字居中后的width
// 表示这段文字在图片上的位置(x,y) 第一个是你设置的内容
g2.drawString(realStationName,widthX,70); //此处的70是指放置居中后的文字的水平位置
g2.setFont(new Font("楷体",Font.BOLD,48));
g2.drawString(PileNumber+"号桩",25,154);
g2.setFont(new Font("黑体",Font.BOLD,130));
g2.drawString(letter,250,180);
g2.setFont(new Font("楷体",Font.BOLD,60));
g2.drawString("",320,174);
File dest = fullImgdestPath;
ImageIO.write(bottomImg, "png", dest);
}
}

View File

@ -37,15 +37,24 @@ public class QrImgUtils {
//3.拼接成完整图片
//3.1生成指定规则的图片名
String finallyImgFileName = DateUtil.format(new Date(), "yyyyMMddHHmmssSSS") + serialNumber + ".png";
new ImageUtil().createXhImg(
// new ImageUtil().createXhImg(
// new File(environment.getProperty("oss.bottomImg")),
// QrCode,
// new File(environment.getProperty("oss.bottomLogoImg")),
// serialNumber,
// new File(environment.getProperty("oss.fullImgDestPath")+finallyImgFileName),
// chargingStationName,
// String.valueOf(xhpcTerminal.getNumber()),
// String.valueOf(letterMap.get(forIndex)));
new ImageUtil().fastCreateImg(
new File(environment.getProperty("oss.bottomImg")),
QrCode,
new File(environment.getProperty("oss.bottomLogoImg")),
serialNumber,
new File(environment.getProperty("oss.fullImgDestPath")+finallyImgFileName),
chargingStationName,
String.valueOf(xhpcTerminal.getNumber()),
String.valueOf(letterMap.get(forIndex)));
String.valueOf(letterMap.get(forIndex)),
new File(environment.getProperty("oss.fullImgDestPath")+finallyImgFileName)
);
//4.上传图片至服务器
// 创建OSSClient实例
@ -58,22 +67,16 @@ public class QrImgUtils {
Long terminalId = xhpcTerminal.getTerminalId();
xhpcImgMapper.insert(xhpcTerminal.getPileSerialNumber() + "/" + finallyImgFileName, terminalId);
// //6.删除生成的二维码图片
// File QrImg = new File(environment.getProperty("oss.destPath") + "\\" + qrFileName);
// //7.删除生成本地生成的完整图片
// File finallyImg = new File(environment.getProperty("oss.destPath") + "\\" + finallyImgFileName);
// if (QrImg.exists()) {
// QrImg.delete();
// } else {
// throw new RuntimeException("名字为" + fileName + "的二维码不存在");
// }
//6.删除生成的二维码图片
File QrImg = new File(environment.getProperty("oss.destPath") + "\\" + qrFileName);
QrImg.delete();
//7.删除生成本地生成的完整图片
File finallyImg = new File(environment.getProperty("oss.fullImgDestPath") + finallyImgFileName);
finallyImg.delete();
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
}
}