基于SpringBoot實(shí)現(xiàn)圖片上傳并生成縮略圖功能
在實(shí)際開發(fā)中,上傳圖片并生成縮略圖是一項(xiàng)常見需求,例如在電商平臺(tái)、社交應(yīng)用等場(chǎng)景中,縮略圖可以有效提高頁(yè)面加載速度,優(yōu)化用戶體驗(yàn)。本文將介紹如何在 Spring Boot 項(xiàng)目中實(shí)現(xiàn)上傳圖片并生成縮略圖的功能。
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. 核心代碼實(shí)現(xiàn)
以下方法將實(shí)現(xiàn)圖片上傳并生成縮略圖的功能:
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();
// 計(jì)算縮略圖尺寸
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 方法上傳到對(duì)象存儲(chǔ))
try (FileInputStream in = new FileInputStream(thumbnailFile)) {
String name = getSuffixName(originalStorageName, "/", 1);
storageFileName = uploadFile(bucketName, in, multipartFile.getContentType(), assocId, thumbnailFile.length(), name, "thumbnail");
}
// 清理臨時(shí)文件
new File(originalImagePath).delete();
thumbnailFile.delete();
} catch (IOException e) {
e.printStackTrace();
}
}
return storageFileName;
}3. 計(jì)算縮略圖尺寸方法
根據(jù)原始尺寸、比例、指定寬高生成合適的縮略圖尺寸:
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 {
// 默認(rèn)縮小為原始尺寸的 50%
return new int[]{originalWidth / 2, originalHeight / 2};
}
}4. 工具方法示例
用于提取文件后綴名:
5. 注意事項(xiàng)
- 操作系統(tǒng)臨時(shí)目錄:根據(jù)不同操作系統(tǒng),創(chuàng)建不同的臨時(shí)文件夾路徑。
- 文件清理:上傳完成后及時(shí)刪除臨時(shí)文件,避免占用過(guò)多磁盤空間。
- 縮略圖格式支持:目前支持 PNG、JPG、JPEG、GIF 格式。
- 上傳邏輯:
uploadFile方法需根據(jù)具體的存儲(chǔ)服務(wù)(例如 MinIO、OSS、七牛云等)自定義實(shí)現(xiàn)。
6. 總結(jié)
通過(guò)以上步驟,我們成功實(shí)現(xiàn)了圖片上傳并生成縮略圖的功能。此功能不僅能有效減少圖片加載時(shí)間,還能節(jié)省存儲(chǔ)空間,提升系統(tǒng)性能。
到此這篇關(guān)于基于SpringBoot實(shí)現(xiàn)圖片上傳并生成縮略圖功能的文章就介紹到這了,更多相關(guān)SpringBoot圖片上傳并生成縮略圖內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringMvc+Mybatis+Pagehelper分頁(yè)詳解
這篇文章主要介紹了SpringMvc+Mybatis+Pagehelper分頁(yè)詳解,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下的相關(guān)資料2017-01-01
springboot整合mybatis plus與druid詳情
這篇文章主要介紹了springboot整合mybatis plus與druid詳情,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的下伙伴可以參考一下2022-09-09
SpringBoot使用前綴樹過(guò)濾敏感詞的方法實(shí)例
Trie也叫做字典樹、前綴樹(Prefix Tree)、單詞查找樹,特點(diǎn):查找效率高,消耗內(nèi)存大,這篇文章主要給大家介紹了關(guān)于SpringBoot使用前綴樹過(guò)濾敏感詞的相關(guān)資料,需要的朋友可以參考下2022-01-01
MyBatis如何通過(guò)xml方式實(shí)現(xiàn)SaveOrUpdate
這篇文章主要講如何通過(guò)xml方式實(shí)現(xiàn)SaveOrUpdate,但是仍然建議在Service中實(shí)現(xiàn),本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2023-06-06
在idea中創(chuàng)建SpringBoot項(xiàng)目
這篇文章主要介紹了在idea中創(chuàng)建SpringBoot項(xiàng)目,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-07-07

