调用imagick做图片等比例压缩5M到100kb


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.im4java.core.ConvertCmd;
import org.im4java.core.IM4JavaException;
import org.im4java.core.IMOperation;

public class IMagickUtils {
	
	public static File IMCompress(String IMPath,File file){
		if(file.length()<1024*516L){ // 比0.5M大的图片压缩处理,否则直接使用
			return file;
		}
		int width = 800;
		int height = 600;
		try {
			SimpleImageInfo imageInfo = new SimpleImageInfo(new FileInputStream(file));
			width = imageInfo.getWidth();
			height = imageInfo.getHeight();
		} catch (IOException e1) {
			System.out.println("获取图片宽高失败,Imagickutils.java");
		}
		if(width>800){ // 按比例压缩图片大小,宽度最大为800
			 height = (int) (800.0*height/width);
			 width = 800;
		}
		String size = width+"x"+height+"!";
		String filePath = file.getAbsolutePath();
		
		IMOperation operation = new IMOperation();
		operation.addImage(filePath);
		operation.addRawArgs("-thumbnail", size);
		operation.addRawArgs("-quality", "80%");
		operation.addRawArgs("-units", "pixelsperinch");
		operation.addRawArgs("-density", "96");
		operation.addRawArgs("-colorspace","RGB"); // 转成RGB系 避免CMYK模式下的imageIO水印异常
		operation.addRawArgs("-strip");
		operation.addImage(filePath);

		ConvertCmd cmd = new ConvertCmd();
		cmd.setSearchPath(IMPath);  //Windows需要设置,Linux不需要
		try {
			cmd.run(operation);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return file;
	}

	public static void main(String[] args) throws IOException, InterruptedException, IM4JavaException {
		String impath = "D:\\Program Files\\ImageMagick-7.0.7-Q16";
		File file = new File("C:\\Users\\lenovo\\Downloads\\33.jpg");
		file = IMCompress(impath, file);
	}

}

  

优质内容筛选与推荐>>
1、总结2
2、Linux 之 文件内容查看
3、[转贴]请不要做浮躁的人! BBS 水木清华站
4、第37件事 极简设计的3个方面
5、利用ASP远程注册DLL的方法


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号