<dependency> <groupId>net.coobird</groupId> <artifactId>thumbnailator</artifactId> <version>0.4.7</version> </dependency>
@ApiOperation(value = "简单上传:上传图片 并压缩", notes = " " + "<br/>bucketName leysen1855 " + "<br/>objectName xc/20210105test2.jpg") @RequestMapping(value = "putObjectImageCompress", method = RequestMethod.POST) @ResponseBody public CommonResult<PutObjectResult> putObjectImageCompress(@RequestParam("bucketName") String bucketName , @RequestParam("objectName") String objectName, @RequestParam("file") MultipartFile multipartFile) throws Exception { if (multipartFile.getSize() > 10 * 1024 * 1024) { throw new Exception("上传图片大小不能超过10M!"); } InputStream inputStream = multipartFile.getInputStream(); // 把图片读入到内存中 BufferedImage bufImg = ImageIO.read(inputStream); int width = bufImg.getWidth(); int height = bufImg.getHeight(); log.info("{},height:{}", width, height); // 压缩代码 ByteArrayOutputStream bos = new ByteArrayOutputStream(); bufImg = Thumbnails.of(bufImg) // .scale(0.5f) // 比例 // .forceSize(400, 300) .size(400, 400) // .rotate(90) // 转角90°(顺时针) .outputQuality(1f) // outputQuality:输出的图片质量 .outputFormat("jpg") // outputFormat:输出的图片格式 // 水印设置:在图片右下角,水印图片为watermark.png,透明度为50% // .watermark(Positions.BOTTOM_RIGHT, ImageIO.read(new File("watermark.png")), 0.5f) .asBufferedImage(); //先转成jpg格式来压缩,然后在通过OSS来修改成源文件本来的后缀格式 ImageIO.write(bufImg, "jpg", bos); //获取输出流 inputStream = new ByteArrayInputStream(bos.toByteArray()); PutObjectResult putObjectResult = ossClient.putObject(bucketName, objectName, inputStream); return CommonResult.success(putObjectResult); }
官方示例:https://github.com/coobird/thumbnailator/wiki/Examples