Browse Source

2025.05.22 标签维护功能

master
jiayang yue 8 months ago
parent
commit
25bd346395
  1. 310
      src/main/java/com/gaotao/common/utils/ImageUtils.java
  2. 47
      src/main/java/com/gaotao/modules/label/controller/LabelMaintenanceController.java
  3. 48
      src/main/java/com/gaotao/modules/label/entity/LabelMaintenanceData.java
  4. 25
      src/main/java/com/gaotao/modules/label/mapper/LabelMaintenanceMapper.java
  5. 19
      src/main/java/com/gaotao/modules/label/service/LabelMaintenanceService.java
  6. 100
      src/main/java/com/gaotao/modules/label/service/impl/LabelMaintenanceServiceImpl.java
  7. 22
      src/main/resources/mapper/label/LabelMaintenance.xml

310
src/main/java/com/gaotao/common/utils/ImageUtils.java

@ -0,0 +1,310 @@
package com.gaotao.common.utils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Base64;
/*
* @Description 图片工具类
* @Title ImageUtils
* @author Yangzz
* @date 2023/11/27 14:19
*/
public class ImageUtils {
/*
* @Author yzz
* @Description 图片转Base64字符串
* @Date 14/8/2024
* @param imagePath
* @return String
*/
public static String convertImageToBase64(String imagePath) {
String base64Image = "";
try {
// 使用ClassPathResource获取资源
Resource resource = new ClassPathResource(imagePath);
// 读取资源文件并转换为字节数组
try (InputStream imageInFile = resource.getInputStream()) {
byte[] imageData = new byte[(int) resource.contentLength()];
imageInFile.read(imageData);
// 使用Base64编码
base64Image = Base64.getEncoder().encodeToString(imageData);
}
} catch (IOException e) {
e.printStackTrace();
}
return base64Image;
}
/*
* @Author yzz
* @Description 图片转Base64字符串
* @Date 14/8/2024
* @param imagePath
* @return String
*/
public static String imageToBase64String(String imagePath) {
String base64Image = "";
try {
// 创建File对象指向本地文件系统中的图片路径
File file = new File(imagePath);
// 检查文件是否存在
if (!file.exists()) {
System.out.println("文件不存在:" + imagePath);
return null;
}
// 使用FileInputStream读取文件
try (FileInputStream imageInFile = new FileInputStream(file)) {
byte imageData[] = new byte[(int) file.length()];
imageInFile.read(imageData);
// 使用Base64编码
base64Image = Base64.getEncoder().encodeToString(imageData);
}
} catch (IOException e) {
e.printStackTrace();
return null;
}
return base64Image;
}
/*
* @Author yzz
* @Description 图片转Base64字符串
* @Date 14/8/2024
* @param null
*/
public static String imageToBase64String2(String imagePath, float quality) {
String base64Image = "";
try {
// 创建File对象指向本地文件系统中的图片路径
File file = new File(imagePath);
// 检查文件是否存在
if (!file.exists()) {
System.out.println("文件不存在:" + imagePath);
return null;
}
// 读取图片
BufferedImage originalImage = ImageIO.read(file);
// 调整图像尺寸例如将宽高各缩小为原来的50%
int newWidth = originalImage.getWidth() / 2;
int newHeight = originalImage.getHeight() / 2;
BufferedImage resizedImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, newWidth, newHeight, null);
g.dispose();
// 将图像写入字节数组并使用PNG格式
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(resizedImage, "png", baos);
// 使用Base64编码
byte[] imageData = baos.toByteArray();
base64Image = Base64.getEncoder().encodeToString(imageData);
} catch (IOException e) {
e.printStackTrace();
return null;
}
return base64Image;
}
/*
* @Author yzz
* @Description 图片转base64字符串
* @Date 14/8/2024
* @param imagePath
* @return String
*/
public static String imageToBase64StringTest(String imagePath) {
String base64Image = "";
try {
// 创建File对象指向本地文件系统中的图片路径
File file = new File(imagePath);
// 检查文件是否存在
if (!file.exists()) {
System.out.println("文件不存在:" + imagePath);
return null;
}
// 读取图片
BufferedImage originalImage = ImageIO.read(file);
// 将图像写入字节数组并使用PNG格式
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(originalImage, "png", baos);
// 使用Base64编码
byte[] imageData = baos.toByteArray();
base64Image = Base64.getEncoder().encodeToString(imageData);
} catch (IOException e) {
e.printStackTrace();
return null;
}
return base64Image;
}
/*
* @Author yzz
* @Description 文字转透明背景图片
* @Date 14/8/2024
* @param text
* @return String
*/
public static String textToBase64String(String text) {
String base64Image = "";
try {
// 文本内容包含换行符
//String text = "这是第一行文字\n这是第二行文字\n这是第三行文字";
// 将所有类型的换行符统一为 \n
text = text.replace("\r\n", "\n").replace("\r", "\n");
// 字体设置
Font font = new Font("Arial", Font.PLAIN, 40);
// 计算最大文本宽度和总高度
BufferedImage tempImg = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2dTemp = tempImg.createGraphics();
g2dTemp.setFont(font);
FontMetrics fm = g2dTemp.getFontMetrics();
String[] lines = text.split("\n");
int maxWidth = 0;
int totalHeight = 0;
for (String line : lines) {
int lineWidth = fm.stringWidth(line);
maxWidth = Math.max(maxWidth, lineWidth);
totalHeight += fm.getHeight();
}
g2dTemp.dispose();
// 创建透明背景的BufferedImage
BufferedImage image = new BufferedImage(maxWidth, totalHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = image.createGraphics();
// 设置抗锯齿和透明度
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setFont(font);
g2d.setColor(new Color(0, 0, 0, 255)); // 黑色文字完全不透明
// 绘制文本每行独立绘制
int y = fm.getAscent();
for (String line : lines) {
g2d.drawString(line, 0, y);
y += fm.getHeight();
}
g2d.dispose();
// 将图片转换为字节数组
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "png", baos);
byte[] imageBytes = baos.toByteArray();
// 将字节数组编码为Base64字符串
base64Image = Base64.getEncoder().encodeToString(imageBytes);
// 输出Base64字符串
//System.out.println("Base64字符串: " + base64String);
} catch (Exception ex) {
ex.printStackTrace();
}
return base64Image;
}
/**
* 将项目内的JPG图片资源转换为压缩后的PNG格式并返回Base64字符串
* @param imagePath 项目内图片的资源路径例如 "images/sample.jpg"
* @param scale 缩放比例0.0 ~ 1.0例如 0.5 表示将图片尺寸缩小到原来的 50%
* @return 压缩后的PNG格式图片的Base64字符串
* @throws IOException 如果文件读取或写入时出错
*/
public static String convertJpgToPngBase64(String imagePath, double scale) throws IOException {
// 使用ClassPathResource获取项目内的图片资源
Resource resource = new ClassPathResource(imagePath);
// 获取输入流读取图片数据
InputStream inputStream = resource.getInputStream();
// 读取JPG格式的输入图片
BufferedImage jpgImage = ImageIO.read(inputStream);
// 计算压缩后的宽度和高度
int width = (int) (jpgImage.getWidth() * scale);
int height = (int) (jpgImage.getHeight() * scale);
// 创建压缩后的图片
Image scaledImage = jpgImage.getScaledInstance(width, height, Image.SCALE_SMOOTH);
BufferedImage compressedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
// 将压缩后的图片绘制到BufferedImage上
Graphics2D g2d = compressedImage.createGraphics();
g2d.drawImage(scaledImage, 0, 0, null);
g2d.dispose();
// 创建一个字节数组输出流用于保存PNG图片的字节数据
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
// 将压缩后的图片写入输出流以PNG格式输出
ImageIO.write(compressedImage, "png", outputStream);
// 将输出流转换为字节数组
byte[] pngBytes = outputStream.toByteArray();
// 将字节数组编码为Base64字符串
String base64String = Base64.getEncoder().encodeToString(pngBytes);
// 关闭流
inputStream.close();
outputStream.close();
return base64String;
}
public static void main(String[] args) throws IOException {
// 示例用法
/*String imagePath = "D:\\ckp-file\\2024-08-01\\4d09dd5f-8f49-41dd-90f0-2aa23eaa7f95.png";
String base64Image1 = imageToBase64String(imagePath);
String base64Image2 = imageToBase64String(imagePath,1f);
String base64Image3 = imageToBase64StringTest(imagePath);
System.out.println("Base64 encoded image WYS:\n" + base64Image1);
System.out.println("Base64 encoded image YS:\n" + base64Image2);
System.out.println("Base64 encoded image YS:\n" + base64Image3);*/
String imagePath = "static/img/logoR.jpg";
String base64Image1 = convertJpgToPngBase64(imagePath,0.8);
System.out.println("Base64 encoded image WYS:\n" + base64Image1);
/*String imagePath = "IC:3356B-TR7240R\nContainslC:3356B-WRTZ2000";
String s = textToBase64String(imagePath);
System.out.println(s);*/
}
}

47
src/main/java/com/gaotao/modules/label/controller/LabelMaintenanceController.java

@ -0,0 +1,47 @@
package com.gaotao.modules.label.controller;
import com.gaotao.common.utils.PageUtils;
import com.gaotao.common.utils.R;
import com.gaotao.modules.label.entity.LabelMaintenanceData;
import com.gaotao.modules.label.service.LabelMaintenanceService;
import com.gaotao.modules.manufacturer.data.ManufacturerInformationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
/**
* @description:
* @author: jiayang_yue
* @date: 2025/5/22 17:17
* @param:
* @return:
*/
@RestController
@RequestMapping("/label/maintenance")
public class LabelMaintenanceController {
@Autowired
private LabelMaintenanceService labelMaintenanceService;
/**
* @description: 获取图片列表
* @author: yjy
* @date: 2025/5/22 17:17
* @param: [data]
* @return: com.gaotao.common.utils.R
**/
@PostMapping
@ResponseBody
public R labelMaintenanceInfoSearch(@RequestBody LabelMaintenanceData data) {
PageUtils page = labelMaintenanceService.labelMaintenanceInfoSearch(data);
return R.ok().put("page", page);
}
@PostMapping("/upload")
@ResponseBody
public R uploadLabelMaintenancePicture(@RequestParam("file") MultipartFile file,
@ModelAttribute LabelMaintenanceData data) {
labelMaintenanceService.upload(file,data);
return R.ok();
}
}

48
src/main/java/com/gaotao/modules/label/entity/LabelMaintenanceData.java

@ -0,0 +1,48 @@
package com.gaotao.modules.label.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.gaotao.common.utils.QueryPage;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;
/**
* @TableName base_picture
*/
@TableName(value ="base_picture")
@Data
public class LabelMaintenanceData extends QueryPage {
@TableId(value = "picture_no",type = IdType.AUTO)
private Long pictureNo;
@TableField(value = "picture_desc")
private String pictureDesc;
private String pictureUrl;
private String pictureFileName;
private String pictureNewFileName;
private String pictureType;
private String createBy;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createTime;
private String certificationNo;
@TableField(exist = false)
private String pictureBase64;
@TableField(exist = false)
private String userName;
}

25
src/main/java/com/gaotao/modules/label/mapper/LabelMaintenanceMapper.java

@ -0,0 +1,25 @@
package com.gaotao.modules.label.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gaotao.modules.label.entity.LabelMaintenanceData;
import com.gaotao.modules.manufacturer.data.ManufacturerInformationData;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
/**
* @author jia
* @description 针对表base_picture的数据库操作Mapper
* @createDate 2025-05-22 17:09:18
* @Entity com/gaotao/modules/label.entity.BasePictureData
*/
@Mapper
public interface LabelMaintenanceMapper extends BaseMapper<LabelMaintenanceData> {
IPage<LabelMaintenanceData> labelMaintenanceInfoSearch(Page<LabelMaintenanceData> labelMaintenanceDataPage,@Param("query") LabelMaintenanceData data);
}

19
src/main/java/com/gaotao/modules/label/service/LabelMaintenanceService.java

@ -0,0 +1,19 @@
package com.gaotao.modules.label.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.gaotao.common.utils.PageUtils;
import com.gaotao.modules.label.entity.LabelMaintenanceData;
import com.gaotao.modules.manufacturer.data.ManufacturerInformationData;
import org.springframework.web.multipart.MultipartFile;
/**
* @author jia
* @description 针对表base_picture的数据库操作Service
* @createDate 2025-05-22 17:09:18
*/
public interface LabelMaintenanceService extends IService<LabelMaintenanceData> {
PageUtils labelMaintenanceInfoSearch(LabelMaintenanceData data);
void upload(MultipartFile file, LabelMaintenanceData data);
}

100
src/main/java/com/gaotao/modules/label/service/impl/LabelMaintenanceServiceImpl.java

@ -0,0 +1,100 @@
package com.gaotao.modules.label.service.impl;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gaotao.common.utils.ImageUtils;
import com.gaotao.common.utils.PageUtils;
import com.gaotao.modules.label.entity.LabelMaintenanceData;
import com.gaotao.modules.label.mapper.LabelMaintenanceMapper;
import com.gaotao.modules.label.service.LabelMaintenanceService;
import com.gaotao.modules.manufacturer.data.ManufacturerInformationData;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;
import java.util.UUID;
/**
* @author jia
* @description 针对表base_picture的数据库操作Service实现
* @createDate 2025-05-22 17:09:18
*/
@Service
public class LabelMaintenanceServiceImpl extends ServiceImpl<LabelMaintenanceMapper, LabelMaintenanceData>
implements LabelMaintenanceService {
@Override
public PageUtils labelMaintenanceInfoSearch(LabelMaintenanceData data) {
IPage<LabelMaintenanceData> resultList = baseMapper.labelMaintenanceInfoSearch(new Page<LabelMaintenanceData>(data.getPage(), data.getLimit()), data);
List<LabelMaintenanceData> pictureData = resultList.getRecords();
for (int i = 0; i <pictureData.size(); i++) {
if (!(pictureData.get(i).getPictureUrl() == null || "".equals(pictureData.get(i).getPictureUrl()))){
String base64iMG = ImageUtils.imageToBase64String(pictureData.get(i).getPictureUrl());
pictureData.get(i).setPictureBase64("data:image/"+pictureData.get(i).getPictureType()+";base64,"+base64iMG);
}
}
resultList.setRecords(pictureData);
return new PageUtils(resultList);
}
@Override
public void upload(MultipartFile file, LabelMaintenanceData data) {
// 定义文件保存的根路径
String rootPath = "D:/ckp-file/";
// 创建存储的日期目录/2022-01-25/
String datePath = LocalDate.now().toString();
Path fullPath = Paths.get(rootPath, datePath);
// 判断目录是否存在不存在则创建
try {
Files.createDirectories(fullPath);
} catch (IOException e) {
// 处理异常
throw new RuntimeException(e);
}
// 将文件保存到路径下
try {
String fileName = file.getOriginalFilename();
assert fileName != null;
String extension = fileName.substring(fileName.lastIndexOf('.'));
// 定义新的文件名
String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
String newFileName = UUID.randomUUID()+ extension;
Path filePath = Paths.get(fullPath.toString(), newFileName);
// 判断文件类型 是否是图片
if (!fileType.equalsIgnoreCase("jpg") &&!fileType.equalsIgnoreCase("png") &&!fileType.equalsIgnoreCase("jpeg")) {
// 不是图片抛出异常
throw new RuntimeException("请上传 jpg,png,jpeg 格式的图片!");
}
String certificationNo = data.getCertificationNo();
file.transferTo(filePath.toFile());
data.setPictureType(fileType);
data.setPictureUrl(filePath.toString());
data.setPictureFileName(fileName);
data.setPictureNewFileName(newFileName);
data.setCertificationNo(null);
data.setCreateTime(new Date());
baseMapper.insert(data);
if (certificationNo.equals("CC")){
data.setCertificationNo("A" + data.getPictureNo());
baseMapper.updateById(data);
}
} catch (IOException e) {
// 处理异常
throw new RuntimeException(e);
}
}
}

22
src/main/resources/mapper/label/LabelMaintenance.xml

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.gaotao.modules.label.mapper.LabelMaintenanceMapper">
<select id="labelMaintenanceInfoSearch" resultType="com.gaotao.modules.label.entity.LabelMaintenanceData">
SELECT * FROM base_picture
<where>
<if test="query.pictureDesc != null and query.pictureDesc != ''">
AND picture_desc like #{query.pictureDesc}
</if>
<if test="query.certificationNo == 'CC'">
AND certification_no is not null
</if>
<if test="query.certificationNo == 'BB'">
AND certification_no is null
</if>
</where>
order by create_time desc
</select>
</mapper>
Loading…
Cancel
Save