1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | 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); } } |
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步