mogrify 下载地址:http://www.imagemagick.org/script/binary-releases.php#windows
cmd执行结果:
mogrify -colorspace RGB -quality 100 "D:\software\eclipse\workspace2\demo_channel_terminal\src\main\resources\mini.jpg"
说明:最后一个参数是要转化的图片全路径.
那么如何使用Java 来调用呢?
测试代码:
- @Test
- public void test02()
- {
- Process p = null;
- String []command = null;
- command = new String[]{"cmd"," /c ","mogrify.exe" ,"-colorspace", "RGB", "-quality" ,"100" ,"\"D:\\software\\eclipse\\workspace2\\demo_channel_terminal\\src\\main\\resources\\mini.jpg\""};//cmd /c is needed
- BufferedReader reader = null;
- try
- {
- p = Runtime.getRuntime().exec(command, null);//)
- reader = new BufferedReader(new InputStreamReader(p
- .getErrorStream(),"gbk"));
- StringBuilder sb = new StringBuilder();
- String readedLine = null;
- try
- {
- while ((readedLine = reader.readLine()) != null)
- {
- sb.append(readedLine);
- sb.append("\r\n");
- }
- }
- catch (IOException e)
- {
- e.printStackTrace();
- }
- finally
- {
- try
- {
- reader.close();
- p.destroy();
- }
- catch (IOException e)
- {
- e.printStackTrace();
- }
- }
- String content = sb.toString();
- System.out.println(content);
- }
- catch (IOException e)
- {
- e.printStackTrace();
- }
- }
执行报错:
'mogrify.exe' 不是内部或外部命令,也不是可运行的程序
或批处理文件。
但是我在命令行里面执行没有问题呀!!!
为什么命令行里面没问题,java调用就有问题呢?
最后找到了原因:java执行本地命令时要指定命令(exe文件)所在路径
String commandFolder="D:\\Program Files\\ImageMagick-6.8.9-Q16\\";
p = Runtime.getRuntime().exec(command, null,new File(commandFolder/*命令的所在目录*/));//)
reader = new BufferedReader(new InputStreamReader(p
.getErrorStream(),"gbk"));
正确的代码如下:
- @Test
- public void test02()
- {
- Process p = null;
- String []command = null;
- // command = new String[]{"cmd"," /c ","dir"};//cmd /c is needed
- command = new String[]{"cmd"," /c ","mogrify.exe" ,"-colorspace", "RGB", "-quality" ,"100" ,"\"D:\\software\\eclipse\\workspace2\\demo_channel_terminal\\src\\main\\resources\\mini.jpg\""};//cmd /c is needed
- BufferedReader reader = null;
- try
- {
- String commandFolder="D:\\Program Files\\ImageMagick-6.8.9-Q16\\";
- p = Runtime.getRuntime().exec(command, null,new File(commandFolder/*命令的所在目录*/));//)
- reader = new BufferedReader(new InputStreamReader(p
- .getErrorStream(),"gbk"));
- StringBuilder sb = new StringBuilder();
- String readedLine = null;
- try
- {
- while ((readedLine = reader.readLine()) != null)
- {
- sb.append(readedLine);
- sb.append("\r\n");
- }
- }
- catch (IOException e)
- {
- e.printStackTrace();
- }
- finally
- {
- try
- {
- reader.close();
- p.destroy();
- }
- catch (IOException e)
- {
- e.printStackTrace();
- }
- }
- String content = sb.toString();
- System.out.println(content);
- }
- catch (IOException e)
- {
- e.printStackTrace();
- }
- }
mogrify网盘下载地址:http://pan.baidu.com/s/1i3vHPOh
安装完成之后目录情况:
参考:http://iaiai.iteye.com/blog/1461370
注意:
(1)java 执行dir或ipconfig的命令不需要执行命令所在目录,但是执行用户安装上的exe就必须执行命令所在目录;
(2)java执行操作系统命令时一定要加上"cmd /c"