Tip:據(jù)說(shuō)淘寶使用此軟件進(jìn)行圖片壓縮
前提條件
- 下載GraphicsMagick
- 添加Im4Java依賴
<dependency>
<groupId>org.im4java</groupId>
<artifactId>im4java</artifactId>
<version>1.4.0</version>
</dependency>
實(shí)現(xiàn)
public static void compress(String graphicsMagickHome,String sourcePath, String targetPath, double quality) throws InterruptedException, IOException, IM4JavaException {
GMOperation op = new GMOperation();
//待處理圖片的絕對(duì)路徑
op.addImage(sourcePath);
//圖片壓縮比,有效值范圍是0.0-100.0,數(shù)值越大,縮略圖越清晰 s
op.quality(quality);
//width 和height可以是原圖的尺寸,也可以是按比例處理后的尺寸
// op.addRawArgs("-resize", "100");
//寬高都為100
//op.addRawArgs("-resize", "100x100");
op.addRawArgs("-gravity", "center");
//op.resize(100, null);
//處理后圖片的絕對(duì)路徑
File smallFile = new File(targetPath);
if (!smallFile.getParentFile().exists()) {
smallFile.mkdir();
}
op.addImage(targetPath);
// 如果使用ImageMagick,設(shè)為false,使用GraphicsMagick,就設(shè)為true,默認(rèn)為false
ConvertCmd convert = new ConvertCmd(true);
String osName = System.getProperty("os.name").toLowerCase();
if (osName.contains("win")) {
//linux下不要設(shè)置此值,不然會(huì)報(bào)錯(cuò)
convert.setSearchPath(graphicsMagickHome);
}
convert.run(op);
}
說(shuō)明
- graphicsMagickHome:GraphicsMagick的home目錄,只有windows下需要,linux不需要,傳null即可
- sourcePath: 圖像源絕對(duì)路徑
- targetPath: 生成圖像的目標(biāo)絕對(duì)路徑
- quality:生成圖片的質(zhì)量,0-100.0,根據(jù)實(shí)際情況自己設(shè)定