Skip to content

Commit

Permalink
feat: 图片默认压缩到不超过1MB
Browse files Browse the repository at this point in the history
  • Loading branch information
1962247851 committed Jun 17, 2024
1 parent 6bb2c77 commit 84e6757
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 11 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,9 @@ public class UpmsConstants {

public static final String SERVICE_URL = "http://" + SERVICE_NAME;

/**
* 若支持压缩,压缩到不超过1MB(1024 * 1024B)
*/
public static final int MAX_FILE_SIZE = 1024 * 1024;

}
Original file line number Diff line number Diff line change
Expand Up @@ -54,15 +54,14 @@
import tech.ordinaryroad.commons.minio.response.DownloadResponses;
import tech.ordinaryroad.commons.minio.service.OrMinioService;
import tech.ordinaryroad.commons.mybatis.utils.PageUtils;
import tech.ordinaryroad.upms.constant.UpmsConstants;
import tech.ordinaryroad.upms.dto.SysFileDTO;
import tech.ordinaryroad.upms.entity.SysFileDO;
import tech.ordinaryroad.upms.mapstruct.SysFileMapStruct;
import tech.ordinaryroad.upms.request.SysFileQueryRequest;
import tech.ordinaryroad.upms.service.SysFileService;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.*;
import java.net.URLEncoder;
import java.time.LocalDateTime;

Expand Down Expand Up @@ -93,21 +92,30 @@ public Result<String> upload(@RequestParam String clientId, @RequestParam String
String dateString = DateUtil.format(LocalDateTime.now(), DatePattern.NORM_DATE_PATTERN);

// 是否需要压缩 大于1MB并且支持压缩
boolean needCompress = file.getSize() > 1024 * 1024;
if (needCompress) {
needCompress = ThumbnailatorUtils.isSupportedOutputFormat(extName);
}
boolean needCompress = file.getSize() > UpmsConstants.MAX_FILE_SIZE && ThumbnailatorUtils.isSupportedOutputFormat(extName);

// 保存缩略图
if (needCompress) {
try {
// 缩略图临时文件
File tempFile = FileUtil.createTempFile(prefix, suffix, null, true);
@Cleanup ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
@Cleanup InputStream inputStream = file.getInputStream();
Thumbnails.of(inputStream)
.scale(0.5)
.outputQuality(0.6)
.toFile(tempFile);

long currentSize = 0;
do {
inputStream = currentSize == 0 ? inputStream : new ByteArrayInputStream(outputStream.toByteArray());
outputStream.reset();

Thumbnails.of(inputStream)
.scale(0.9)
.toOutputStream(outputStream);

currentSize = outputStream.size();
} while (currentSize > UpmsConstants.MAX_FILE_SIZE);

outputStream.writeTo(new FileOutputStream(tempFile));

// 保存缩略图
String objectName = String.format("/%s/thumbnail/%s", dateString, filename);
@Cleanup FileInputStream tempFileInputStream = new FileInputStream(tempFile);
Expand Down

0 comments on commit 84e6757

Please sign in to comment.