public void thumbnail(PutObjectRequest request, UploadParam param) throws IOException {
if (ObjectUtils.isEmpty(param.getThumbnail()) || !param.getThumbnail()) {
return;
}
String fileExtension = getFileExtension(request.getObjectKey());
List<String> fileExtensionList = Arrays.asList(obsConfig.getImgType().toString().split(","));
if (!fileExtensionList.contains(fileExtension)) {
return;
}
BufferedImage originalImage = ImageIO.read(param.getUploadFile().getInputStream());
// 获取原始图片宽度
int originalWidth = originalImage.getWidth();
// 获取原始图片高度
int originalHeight = originalImage.getHeight();
//计算宽高比例
double ratio = (double) originalWidth / originalHeight;
// 设置压缩后图片的宽度
int targetWidth = param.getTargetWidth(); // 设置压缩后图片的宽度为100px
// 根据宽高比例计算压缩后图片的高度
int targetHeight = (int) (targetWidth / ratio);
BufferedImage resizedImage = new BufferedImage(targetWidth, targetHeight, originalImage.getType());
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, targetWidth, targetHeight, null);
g.dispose();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(resizedImage, fileExtension, byteArrayOutputStream);
InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
try (ObsClient obsClient = new ObsClient(obsConfig.getAk(), obsConfig.getSk(), obsConfig.getEndPoint())) {
PutObjectRequest thumbnailRequest = new PutObjectRequest();
thumbnailRequest.setBucketName(obsConfig.getBucketName());
thumbnailRequest.setObjectKey("thumbnail/" + request.getObjectKey());
thumbnailRequest.setAcl(AccessControlList.REST_CANNED_PRIVATE);
thumbnailRequest.setInput(inputStream);
PutObjectResult result = obsClient.putObject(thumbnailRequest);
String url = generateObjectUrl(result);
log.info("{} upload img : {}", param.getUserName(), url);
} catch (ObsException e) {
log.error("HTTP Code: " + e.getResponseCode());
log.error("Error Code:" + e.getErrorCode());
log.error("Error Message: " + e.getErrorMessage());
log.error("Request ID:" + e.getErrorRequestId());
log.error("Host ID:" + e.getErrorHostId());
} catch (Exception e) {
log.error("其他错误: " + e.getMessage());
} finally {
byteArrayOutputStream.close();
}
}
@Data
public class UploadParam {
private MultipartFile uploadFile;
private String userName;
private String type;
private Boolean byName;
private Boolean thumbnail;
private Integer targetWidth;
public UploadParam() {
this.thumbnail = false;
this.targetWidth = 100;
}
}