GraphicsMagick圖片壓縮工具類

Tip:據說淘寶使用此軟件進行圖片壓縮

前提條件

<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,根據實際情況自己設定
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容