Java中缩放图片的方法比较多,如JDK本身读写图片,或者使用第三方Jmagic,或者 thumbnails等。Jimi也是另外一种通过java调用操作图片的工具包。
注意:
JimiProClasses.zip下载地址: http://www.animal.ahrgr.de/download/JimiProClasses.zip
这个包差了四个最很要的类,可以在这儿下载 http://www.fmsware.com/stuff/gif.zip
具体更新信息可参考:http://java.sun.com/products/jimi/
然后打成一个包使用,最后将.zip改成.jar即可。缩放方法如下:
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import com.sun.jimi.core.Jimi;
import com.sun.jimi.core.JimiException;
import com.sun.jimi.core.JimiWriter;
/**
* Created on 2011-8-3
* <p>Discription:[图片缩放.指定比例eg: 20即按原大小的20%缩放]</p>
* @param file scale
* @return
* @author:[shixing_11@sina.com]
* @update:[日期YYYY-MM-DD] [更改人姓名]
*/
public static boolean resizeImageByScale(File file, int scale) {
boolean flag = false;
try {
Image image = ImageIO.read(file);
double width = (double) image.getWidth(null);
double height = (double) image.getHeight(null);
int newWidth = (int)Math.floor(width * scale/100d);
int newHeight = (int)Math.floor(height * scale/100d);
BufferedImage tag = new BufferedImage(newWidth,newHeight,BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(image, 0, 0, newWidth, newHeight, null);
OutputStream outputStream = new FileOutputStream(file);
//Jimi.getEncoderTypes()[3]即获取mini-type按jpg格式压缩
JimiWriter writer = Jimi.createJimiWriter(Jimi.getEncoderTypes()[3],outputStream);
writer.setSource(tag);
writer.putImage(outputStream);
outputStream.close();
flag = true;
} catch (JimiException e) {
flag = false;
} catch (Exception e) {
flag = false;
}
return flag;
}