maven里面引入了下面这个包
<!-- https://mvnrepository.com/artifact/net.coobird/thumbnailator --> <dependency> <groupId>net.coobird</groupId> <artifactId>thumbnailator</artifactId> <version>0.4.14</version> </dependency> |
图片压缩:
//filePath(图片路径) //图片压缩 FileInputStream fileInputStream = new FileInputStream(new File(filePath)); BufferedImage originalImage = ImageIO.read(fileInputStream); Thumbnails.of(originalImage) .scale(1f) //图片大小(长宽)压缩比例 从0-1,1表示原图 .outputQuality(0.8) //图片质量压缩比例 从0-1,越接近1质量越好 .toFile(filePath); |
图片缩放:
//filePath(图片路径) //按照比例缩放 FileInputStream fileInputStream = new FileInputStream(new File(filePath)); BufferedImage originalImage = ImageIO.read(fileInputStream); Thumbnails.of(originalImage) .scale(0.5f) //图片大小(长宽)压缩比例 从0-1,1表示原图 .outputQuality(0.8) //图片质量压缩比例 从0-1,越接近1质量越好 .toFile(filePath); //按照尺寸缩放 Thumbnails.of(originalImage) .scale(1f) .size(200, 500) //大小 .outputQuality(0.5f) //质量 .outputFormat("jpg") //图片格式 .useOriginalFormat() //使用原文件格式 .toFile(filePath); |