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