java中使用thumbnailator实现图片压缩
public static void main(String args[]) throws IOException {
// 原始比例大小,0.5倍清晰度
Thumbnails.of(new File("original.jpg")).scale(1f).outputQuality(0.5f).toFile(new File("thumbnail.jpg"));
}
提供一个转换接口示例
Controller
@Slf4j
@RestController
@Api(tags = "服务接口")
@RequestMapping("/image")
public class ImageController {
/**
*
*
* @param file
* @param quality
* @return
*/
@ApiOperation(value = "图片压缩")
@PostMapping("/compress/{quality}")
public ResponseEntity<?> compressImage(@RequestPart @RequestParam("file") MultipartFile file,
@PathVariable("quality") float quality, HttpServletResponse response) {
if (quality <= 0.0f || quality > 1.0f) {
return ResponseEntity.badRequest()
.body("Quality out of range. It must be between 0.0 and 1.0");
}
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
ImageCompressor.compressImage(file.getInputStream(), outputStream, quality);
} catch (IOException e) {
log.error("Failed to compress image:{}, quality:{}", file, quality, e);
return ResponseEntity.status(500).body("Failed to compress image: " + e.getMessage());
}
ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
response.setHeader(Header.CONTENT_TYPE.getValue(), MediaType.IMAGE_JPEG.getType());
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_JPEG);
return ResponseEntity.ok()
.headers(headers)
.body(new InputStreamResource(inputStream));
}
}
实现
@Slf4j
public class ImageCompressor {
@WithSpan("/compress")
public static void compressImage(InputStream inputStream, OutputStream outputStream,
float quality) throws IOException {
// Read input stream into a byte array to calculate the original size
byte[] inputBytes = IOUtils.toByteArray(inputStream);
int originalSize = inputBytes.length;
// If quality is 1, copy the input stream to the output stream without compression
if (quality == 1.0f) {
IOUtils.copy(new ByteArrayInputStream(inputBytes), outputStream);
log.info("Quality is 1, Original size: {} bytes", originalSize);
return;
}
ByteArrayOutputStream tempOutputStream = new ByteArrayOutputStream();
Thumbnails.of(new ByteArrayInputStream(inputBytes))
.scale(1f)
.outputQuality(quality)
.outputFormat("jpg")
.toOutputStream(tempOutputStream);
byte[] outputBytes = tempOutputStream.toByteArray();
int compressedSize = outputBytes.length;
outputStream.write(outputBytes);
Span.current().setAttribute("originalSize", originalSize)
.setAttribute("compressedSize", compressedSize);
log.info("Original size: {} bytes, Compressed size: {} bytes", originalSize, compressedSize);
}
}
调用方式
curl -X POST -F "file=@original.jpg" localhost:8700/image/compress/0.5 --output compressed.jpg