在实际开发中,上传图片并生成缩略图是一项常见需求,例如在电商平台、社交应用等场景中,缩略图可以有效提高页面加载速度,优化用户体验。本文将介绍如何在 spring boot 项目中实现上传图片并生成缩略图的功能。
1. 依赖配置
在 pom.xml 文件中添加以下依赖:
<!-- spring boot web -->
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-web</artifactid>
</dependency>
<!-- 文件上传 -->
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-tomcat</artifactid>
</dependency>
<!-- 图片处理依赖 -->
<dependency>
<groupid>com.twelvemonkeys.imageio</groupid>
<artifactid>imageio-core</artifactid>
<version>3.8.1</version>
</dependency>
<!-- apache commons io -->
<dependency>
<groupid>commons-io</groupid>
<artifactid>commons-io</artifactid>
<version>2.8.0</version>
</dependency>2. 核心代码实现
以下方法将实现图片上传并生成缩略图的功能:
import org.springframework.web.multipart.multipartfile;
import javax.imageio.imageio;
import java.awt.*;
import java.awt.image.bufferedimage;
import java.io.*;
import java.nio.file.files;
import java.nio.file.path;
import java.nio.file.paths;
import java.util.*;
public string uploadpicturethumbnail(string bucketname, multipartfile multipartfile, long associd, string originalstoragename, integer scale, integer width, integer height) {
string directorypath = "";
if (osutils.islinux()) {
directorypath = "/tempdir";
} else if (osutils.iswindows()) {
directorypath = "c:/tempdir";
}
file directory = new file(directorypath);
if (!directory.exists()) {
directory.mkdir();
}
string originalname = multipartfile.getoriginalfilename();
string suffixname = getsuffixname(originalname, ".", 0);
string suffix = getsuffixname(originalname, ".", 1);
string storagename = uuid.randomuuid().tostring() + suffixname;
string storagefilename = null;
list<string> thumbnailsuffixname = arrays.aslist(".png", ".jpg", ".jpeg", ".gif");
if (thumbnailsuffixname.contains(suffixname.tolowercase())) {
try {
// 保存原始图片
string originalimagepath = directorypath + "/" + storagename;
path filepath = paths.get(originalimagepath);
files.write(filepath, multipartfile.getbytes());
// 读取原始图片并生成缩略图
bufferedimage originalimage = imageio.read(new file(originalimagepath));
int originalwidth = originalimage.getwidth();
int originalheight = originalimage.getheight();
// 计算缩略图尺寸
int[] data = computesize(originalwidth, originalheight, scale, width, height);
int thumbnailwidth = data[0];
int thumbnailheight = data[1];
image scaledimage = originalimage.getscaledinstance(thumbnailwidth, thumbnailheight, image.scale_smooth);
bufferedimage thumbnailimage = new bufferedimage(thumbnailwidth, thumbnailheight, bufferedimage.type_int_rgb);
graphics2d g2d = thumbnailimage.creategraphics();
g2d.drawimage(scaledimage, 0, 0, null);
g2d.dispose();
// 保存缩略图
string thumbnailpath = directorypath + "/" + uuid.randomuuid().tostring() + suffixname;
file thumbnailfile = new file(thumbnailpath);
imageio.write(thumbnailimage, suffix.replace(".", ""), thumbnailfile);
// 上传缩略图(这里用自定义 uploadfile 方法上传到对象存储)
try (fileinputstream in = new fileinputstream(thumbnailfile)) {
string name = getsuffixname(originalstoragename, "/", 1);
storagefilename = uploadfile(bucketname, in, multipartfile.getcontenttype(), associd, thumbnailfile.length(), name, "thumbnail");
}
// 清理临时文件
new file(originalimagepath).delete();
thumbnailfile.delete();
} catch (ioexception e) {
e.printstacktrace();
}
}
return storagefilename;
}3. 计算缩略图尺寸方法
根据原始尺寸、比例、指定宽高生成合适的缩略图尺寸:
private int[] computesize(int originalwidth, int originalheight, integer scale, integer width, integer height) {
if (scale != null && scale > 0) {
return new int[]{originalwidth * scale / 100, originalheight * scale / 100};
} else if (width != null && height != null) {
return new int[]{width, height};
} else {
// 默认缩小为原始尺寸的 50%
return new int[]{originalwidth / 2, originalheight / 2};
}
}4. 工具方法示例
用于提取文件后缀名:
5. 注意事项
- 操作系统临时目录:根据不同操作系统,创建不同的临时文件夹路径。
- 文件清理:上传完成后及时删除临时文件,避免占用过多磁盘空间。
- 缩略图格式支持:目前支持 png、jpg、jpeg、gif 格式。
- 上传逻辑:
uploadfile方法需根据具体的存储服务(例如 minio、oss、七牛云等)自定义实现。
6. 总结
通过以上步骤,我们成功实现了图片上传并生成缩略图的功能。此功能不仅能有效减少图片加载时间,还能节省存储空间,提升系统性能。
到此这篇关于基于springboot实现图片上传并生成缩略图功能的文章就介绍到这了,更多相关springboot图片上传并生成缩略图内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论