ImageMagick +Im4java 處理上傳的圖片,截圖,縮略圖,保證高質量
ImageMagick 在windows下是不存在的,linux一般都有(最后也請確認下,可以參考官網,不過也可以簡單的運行convert 命令判斷)。
軟件官網:im4java.sourceforge.net ps 請FQ。
ImageMagick官網: http://www.imagemagick.org/
簡單操作操作:
/** *@author 孫月江 */ import java.io.File; import org.im4java.core.ConvertCmd; import org.im4java.core.IMOperation; import org.im4java.process.ProcessStarter; import org.springframework.util.Assert; public class ImageCropper { private static final String ENV_OS = System.getProperty("os.name").toLowerCase(); private static final String ImageMagickPath = "D:\\software\\ImageMagick"; static { if (isWindows()) { Assert.isTrue(new File(ImageMagickPath).exists(), "you shoud first install ImageMagick software to use cropper in your windows system."); ProcessStarter.setGlobalSearchPath(ImageMagickPath); } } public static void main(String args[]) throws Exception { System.out.println(ENV_OS); String inputFileLocation = "d:/d.jpeg"; String outputFileLocation = "d:/d-res.jpeg"; boolean r = crop(inputFileLocation, outputFileLocation, 50, 50, 200, 140); System.out.println(r); } public static boolean isWindows() { return (ENV_OS.indexOf("win") >= 0); } /** * 按照給定的參數截取圖片區域 * * @param imagePath 原圖位置 * @param newPath 結果圖位置 * @param x 橫坐標 * @param y 縱坐標 * @param width 寬度 * @param height 高度 * @return */ public static boolean crop(String imagePath, String newPath, int x, int y, int width, int height) { boolean flag = false; try { IMOperation op = new IMOperation(); op.addImage(); /** width:裁剪的寬度 * height:裁剪的高度 * x:裁剪的橫坐標 * y:裁剪縱坐標 */ op.crop(width, height, x, y); op.addImage(); ConvertCmd convert = new ConvertCmd(); convert.run(op, imagePath, newPath); flag = true; } catch (Exception e) { e.printStackTrace(); flag = false; } return flag; } /** * 縮放圖片 * * @param imagePath * @param newPath * @param width * @param height * @return */ public static boolean scale(String imagePath, String newPath, int width, int height) { boolean flag = false; try { IMOperation op = new IMOperation(); op.addImage(); op.resize(width, height); op.addImage(); ConvertCmd convert = new ConvertCmd(); convert.run(op, imagePath, newPath); flag = true; } catch (Exception e) { e.printStackTrace(); flag = false; } return flag; } }