图片压缩指定大小范围
图片压缩之后存在上下误差,不影响使用
@RequestMapping(value="/compress",method=RequestMethod.POST)
public void compress(@RequestParam("file") MultipartFile multipartFile,@RequestParam("size")Integer size ,@RequestParam("size2")Integer size2){
//图片输出存放地址
String path = "D://images/100k/"+multipartFile.getOriginalFilename();
File file = new File(path);
try{
Thumbnails.of(multipartFile.getInputStream()).scale(1f).toFile(file);
cyclicCompression(paths,size,size2,0.8)
}catch(IOException e){
e.prinStackTrace();
}
}
/**
* 递归压缩
*/
public static void cyclicCompression(String paths,Integer size,Integer size2,double accurary){
File files = new File(paths);
if(size <= files.length()/1024 <= size2) return;
BufferedImage bim = ImageIO.read(file);
int width = new BigDecimal(bim.getWidth()).multiply(new BigDecimal(accurary)).intValue();
int height = new BigDecimal(bim.getHeight()).multiply(new BigDecimal(accurary)).intValue();
Thumbnails.of(paths).size(width,height).outputQuality(accurary).toFIle(desPath);
cyclicCompression(paths,size,size2,accurary)
}
需要依赖Thumbnails
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.19</version>
</dependency>
7658

被折叠的 条评论
为什么被折叠?



