yinyitong-zhongyuyuan-dll-hang/src/main/java/com/dpkj/modules/autoReplyPrint/utils/ImageUtils.java

86 lines
2.4 KiB
Java
Raw Normal View History

package com.dpkj.modules.autoReplyPrint.utils;
import com.dpkj.common.exception.RRException;
import org.springframework.web.multipart.MultipartFile;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
/**
* 图片转换工具
*
* @author <a href="https://gitee.com/shi-chongli">石头人</a>
* @version 1.0
* @since 2025-01-17 14:06:09
*/
public class ImageUtils {
/**
* 读取图片并转换为byte数组
* @param imagePath 图片路径
* @return byte数组
*/
public static byte[] imageToBytes(String imagePath) {
try (BufferedInputStream bis = new BufferedInputStream(Files.newInputStream(Paths.get(imagePath)));
ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = bis.read(buffer)) != -1) {
baos.write(buffer, 0, bytesRead);
}
return baos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
throw new RRException("读取图片信息失败");
}
}
/**
* 获取文件byte[],通过 MultipartFile
* @param file 文件信息
* @return byte数组
*/
public static byte[] getByteToMultipartFile(MultipartFile file){
// 验证文件是否为空
if (file.isEmpty()) {
throw new RRException("文件内容为空");
}
// 验证文件类型
String contentType = file.getContentType();
if (contentType == null || !contentType.startsWith("image/")) {
throw new RRException("只支持图片文件");
}
// 获取文件扩展名
String fileName = file.getOriginalFilename();
String fileExtension = fileName != null ?
fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase() : "";
// 验证扩展名
List<String> allowedExtensions = Arrays.asList("jpg", "jpeg", "png", "gif");
if (!allowedExtensions.contains(fileExtension)) {
throw new RRException("不支持的文件格式");
}
try {
// 转换为字节数组
return file.getBytes();
}catch (Exception e){
e.printStackTrace();
throw new RRException("获取文件字节失败");
}
}
}