我们经常需要实现图片上传的功能,但是光是上传图片可能还是远远不够的,我们必须对我们上传的图片进行处理,改变大小等等。JMagick是 ImageMagick提供的一套使用Java调用ImageMagick的API接口,功能非常强大,下面介绍如果使用这个API处理图片的大小。引入 JMagick需要的类库:
import magick.ImageInfo;
import magick.MagickException;
import magick.MagickImage;
我们需要把图片保存为 两个尺寸,这里要提前定义两种常量:
public static String SIZENAME_LARGE = "large";
public static String SIZENAME_SMALL = "small";
下面介绍如何使用JMagick,里面用到的ImageUtil稍后会介绍,FileUtil是操作文件的工具类,这里就暂时不介绍了:
MagickImage source = ImageUtil.getMagickImage("image file name");
Map map = processHead(source);
System.out.ptineln(map.get(SIZENAME_LARGE));
System.out.ptineln(map.get(SIZENAME_SMALL));
ImageUtil.getMagickImage(byte[] byte)
public static MagickImage getMagickImage(byte[] byte) throws MagickException { ImageInfo info = new ImageInfo(); return new MagickImage(info, byte); } |
processHead(MagickImage source)
private Map processHead(MagickImage source) throws Exception { //保存图片的临时目录 try { //保存图片的目录 //返回图片地址 |
ImageUtil.regulate(MagickImage source)
public static MagickImage regulate(MagickImage source) throws MagickException { scaled = source.cropImage(rect); |
ImageUtil.resizePhoto(MagickImage source, String destPathName, int maxWidth, int maxHeight)
public static MagickImage resizePhotoStep(MagickImage source, String destPathName, int maxWidth, int maxHeight) throws MagickException {
int width = 0;
int height = 0;
boolean change = true;
width = (int) source.getDimension().getWidth();
height = (int) source.getDimension().getHeight();
if (maxWidth > width && maxHeight > height) {
change = false;
} else {
if (width > 0 && height > 0) {
if (height / width > maxHeight / maxWidth) {
width = width * maxHeight / height;
height = maxHeight;
} else {
height = height * maxWidth / width;
width = maxWidth;
}
}
}
MagickImage scaled = null;
scaled = source.scaleImage(width, height);
scaled.setFileName(destPathName);
return scaled;
}