java 使用 Thumbnails 图片压缩,会失真
<dependency><groupId>net.coobird</groupId><artifactId>thumbnailator</artifactId><version>0.4.8</version></dependency>@Slf4jpublic class A...
·
进入下面小程序可以体验效果:
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.8</version>
</dependency>
@Slf4j
public class App
{
public static void main( String[] args ) throws IOException {
byte[]bytes = FileUtil.imageCompression("/xx/5645.jpg");
FileOutputStream outputStream = new FileOutputStream("/xx/003.jpg");
outputStream.write(bytes);
outputStream.close();
}
}
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.resizers.configurations.ScalingMode;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
/**
* @Author: Garcia
* @CreateDate: 2019/12/10 15:52
* @Description: what it is class?
*/
@Slf4j
public class FileUtil {
/**
* 压缩图片,默认80%
*/
public static byte[] imageCompression(String path){
ByteArrayOutputStream out = null;
try {
File file = new File(path);
long length = file.length()/1024;
if (length<100){
byte[] fileByte = Files.readAllBytes(file.toPath());
return fileByte;
}
double qual = 0.50;
do {
out = new ByteArrayOutputStream();
Thumbnails.of(path).
scalingMode(ScalingMode.BICUBIC).
// 图片缩放90%, 不能和size()一起使用
scale(0.9).
// 图片质量压缩到50%
outputQuality(qual).
toOutputStream(out);
qual=qual-0.1;
}while ((out.size()/1024)>200);
return out.toByteArray();
} catch (IOException e) {
log.error("图片压缩失败",e);
}finally {
if (out!=null){
try {
out.close();
} catch (IOException e) {
log.error("关闭流失败",e);
}
}
}
return null;
}
}
更多推荐
已为社区贡献2条内容
所有评论(0)