MultipartFile
MultipartFile接口是InputStreamSource的扩展.。
文档原话:
A representation of an uploaded file received in a multipart request.
The file contents are either stored in memory or temporarily on disk. In either case, the user is responsible for copying file contents to a session-level or persistent store as and if desired. The temporary storage will be cleared at the end of request processing.
使用MultipartFile作为接口类型
@PutMapping("/upload_image")
public HashMap<String, Object> uploadImage(@RequestParam("file") MultipartFile file) throws IOException {
HashMap<String, Object> hashMap = new HashMap<>();
//输出文件的InputStream以便生成BufferedImage,BufferedImage是Image类型的扩展,方便对图像修改
BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
if (!file.isEmpty() && bufferedImage != null) {
String path = imageHandleService.saveImage(bufferedImage);
……
}
return hashMap;
}
BufferedImage转存JEPG文件
private Boolean conversionJpegFile(BufferedImage bufferedImage, String imagePath) throws IOException {
File imageFile = new File(imagePath);
//getParentFile()获得File的路径文件夹File
//mkdir()只创建路径上最后的文件夹,mkdirs()则创建路径上所有不存在的文件夹
if (imageFile.getParentFile().exists() || imageFile.getParentFile().mkdirs()) {
//将Buffered存为jepg文件
ImageIO.write(bufferedImage, "jpeg", imageFile);
//清空缓冲区
bufferedImage.flush();
}
if (imageFile.isFile() && imageFile.exists()) {
return true;
} else {
throw new RuntimeException("图片处理失败,目录或文件未被创建");
}
}
定高/宽压缩
private BufferedImage resizeByHeight(BufferedImage bufferedImage) {
int thumbnailWidth = (int) (bufferedImage.getWidth() * (this.thumbnailHigh / (double) bufferedImage.getHeight()));
//SCALE_SMOOTH的缩略算法,生成缩略图片的平滑度优先级比速度高,生成的图片质量比较好,但速度慢
BufferedImage newBufferedImage = new BufferedImage(thumbnailWidth, this.thumbnailHigh, BufferedImage.TYPE_INT_RGB);
//绘制缩小后的图,第一个参数是buffer,中间参数是左上角坐标和宽度高度,最后一个参数是ImageObserver类型
newBufferedImage.getGraphics().drawImage(bufferedImage, 0, 0, thumbnailWidth, this.thumbnailHigh, null);
return newBufferedImage;
}
base64字符串转图像
private BufferedImage decodeBase64ToImage(String base64) throws IOException {
//字符串中不要出现"data:image/png;base64," 这样的字符
byte[] decoderBytes = new BASE64Decoder().decodeBuffer(base64);
for (int i = 0; i < decoderBytes.length; ++i) {
if (decoderBytes[i] < 0) {
//调整异常数据
decoderBytes[i] += 256;
}
}
return ImageIO.read(new ByteArrayInputStream(decoderBytes));
}
删除目标路径上的文件
public static Boolean removeFile(String sPath) {
File file = new File(sPath);
// 路径为文件且不为空则进行删除,不能删除文件夹
return file.isFile() && file.exists() && file.delete();
}