im4java是ImageMagick的一个Java开源接口。与JMagick不同之处在于im4java只是生成与ImageMagick相对应的命令行,然后将生成的命令行传至选中的ImageCommand(使用java.lang.ProcessBuilder.start()实现)来执行相应的操作。它支持大部分ImageMagick命令,可以针对不同组的图片多次复用同一个命令行。
原生java的图片处理效率比较低,而且内存占用高,使用GMagick可以高效的处理图片。
测试代码:
引入maven包
<dependency>
<groupId>org.im4java</groupId>
<artifactId>im4java</artifactId>
<version>1.4.0</version>
</dependency>
/**
* 测试MagickImage处理图片
* Created by zhangrenli on 2018\1\24 0024.
*/
public class MagickTest extends BaseTest{
/**
* 旋转角度
*/
@Test
public void testRotate() {
IMOperation operation = new IMOperation();
operation.addImage("d:\\1.jpg");
operation.rotate(-90d);
operation.addImage("d:\\1_rotate.jpg");
ConvertCmd convertCmd = new ConvertCmd();
convertCmd.setSearchPath("D:\\Program Files\\ImageMagick-6.9.9-Q16");
try {
convertCmd.run(operation);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IM4JavaException e) {
e.printStackTrace();
}
}
/**
* 测试获取图片、截取图片、ocr识别
*/
@Test
public void testCut() {
String picUrl = "http://caxs-cardata-sit.oss-cn-beijing.aliyuncs.com/cardata/2017/08/04/4984305/498174AE-C19D-45D2-8113-1D6B29B44281.jpg?Expires=1516783136&OSSAccessKeyId=LTAIrJPeWdddA3rc&Signature=201boPnLQwD0ob2nwxtm6EQj8b8%3D";
URL url = null;
try {
url = new URL(picUrl);
} catch (MalformedURLException e) {
e.printStackTrace();
}
BufferedImage bi = null;
try {
bi = ImageIO.read(url);
} catch (IOException e) {
e.printStackTrace();
}
byte[] by = MagickUtil.cutPic(bi, 0d);
AipOcr client = BaiduOcrUtils.getAipOcr();
JSONObject response = client.basicGeneral(by, new HashMap<String, String>());
JSONArray jsonArray = response.getJSONArray("words_result");
System.out.println(jsonArray.toString());
}
}
/**
* Magick图片处理工具
* @author zhangrenli
* @date 2018\1\24 0024
*/
public class MagickUtil {
/**
* 旋转、截取图片后返回字节数组
* @param bufferedImage 图片流
* @param angle 旋转角度
* @return 处理后的图片字节数组
*/
public static byte[] cutPic(BufferedImage bufferedImage, Double angle) {
int width = bufferedImage.getWidth();
int height = bufferedImage.getHeight();
IMOperation operation = new IMOperation();
// input
operation.addImage();
// 旋转
operation.rotate(angle);
// 截图
operation.crop(width, height / 4, width / 10, 0);
// output 标准输出
operation.addImage("jpg:-");
ConvertCmd convertCmd = new ConvertCmd();
convertCmd.setSearchPath("D:\\Program Files\\ImageMagick-6.9.9-Q16");
Stream2BufferedImage output = new Stream2BufferedImage ();
convertCmd.setOutputConsumer(output);
try {
// 执行命令并输出
convertCmd.run(operation, bufferedImage);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IM4JavaException e) {
e.printStackTrace();
} finally {
bufferedImage.flush();
}
// 获取处理后输出的BufferedImage
BufferedImage outputImage = output.getImage();
byte[] bytes = null;
try {
bytes = DownLoadPicUtil.getByte(outputImage);
} catch (Exception e) {
e.printStackTrace();
}
return bytes;
}
}