Runtime.exec()调用imageMagick实现图片缩放
直接上代码
public class PictureZoomUtils {private static Log logger = LogFactory.getLog(PictureZoomUtils.class);/** * image magick convert.exe的绝对路径 */private String convertExe;public void zoom(File input, File output, int width, int height) throws Exception {StringBuilder command = new StringBuilder();command.append(convertExe).append(" ").append(input.getAbsolutePath()).append(" -resize ").append(width).append("x").append(height)// 改变尺寸 -resize 120x120.append(" -colors").append(" 100") // 颜色数:设定图片采用的颜色数,如果是生成png或gif图片应指定这个参数.append(" +profile "*" ") // 图片中不存储附加信息,必须使用,否则生成图片过大.append(output.getAbsolutePath());try{Process process = Runtime.getRuntime().exec(command.toString());// any error message?StreamGobbler errorGobbler = new StreamGobbler(process.getErrorStream(), "ERROR");// any output?StreamGobbler outputGobbler = new StreamGobbler(process.getInputStream(), "OUTPUT");errorGobbler.start();outputGobbler.start();process.waitFor(); // 永远要先从标准错误流中读取,然后再读取标准输出流, 最后在执行waitFor}catch(Throwable t){logger.error(t);}}public void setConvertExe(String convertExe) {this.convertExe = convertExe;}public String getConvertExe() {return convertExe;}}class StreamGobbler extends Thread {private static Log logger = LogFactory.getLog(StreamGobbler.class);private InputStream is;private String type; // 输出流的类型ERROR或OUTPUTpublic StreamGobbler(InputStream is, String type) {this.is = is;this.type = type;}public void run() {try {InputStreamReader isr = new InputStreamReader(is);BufferedReader br = new BufferedReader(isr);String line = null;while ((line = br.readLine()) != null) {System.out.println(type + ">" + line);System.out.flush();}} catch (IOException ioe) {logger.error(ioe);}}}