GraphicsMagick圖片壓縮工具類

Tip:據(jù)說(shuō)淘寶使用此軟件進(jìn)行圖片壓縮

前提條件

<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è)定
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容