• 调用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);
    	}
    
    }
    

      

  • 相关阅读:
    leetcode1078
    leetcode417
    我在机器学习踩过的坑,现在告诉你怎么跳过去
    Python相关机器学习‘武器库’
    分别列举人工智能4个主要领域中最牛叉的10位专家
    多巴胺:谷歌开源新型增强学习框架
    AI产品经理成长路
    一个AI产品经理怎么看AI的发展
    机器学习的数学基础
    方差variance, 协方差covariance, 协方差矩阵covariance matrix
  • 原文地址:https://www.cnblogs.com/codeinet/p/8087223.html
Copyright © 2020-2023  润新知