/**
* @param srcURL 原图地址
* @param destURL 缩略图地址
* @param extractBase 压缩基数
* @param scale 压缩限制(宽/高)比例
* @throws Exception
*/
public static void extractPhoto (String srcURL, String destURL, int extractBase, int scale) throws Exception {
File srcFile = new File (srcURL);
Image src = ImageIO.read (srcFile);
int srcHeight = src.getHeight (null);
int srcWidth = src.getWidth (null);
int deskHeight = 0;
int deskWidth = 0;
int srcScale = srcHeight / srcWidth;
if (srcHeight > extractBase || srcWidth > extractBase) {
if (srcScale >= scale || (srcScale != 0 && 1 / srcScale > scale)) {
if (srcScale >= scale) {
deskHeight = extractBase;
deskWidth = srcWidth * deskHeight / srcHeight;
} else {
deskWidth = extractBase;
deskHeight = srcHeight * deskWidth / srcWidth;
}
} else {
if ( srcHeight > extractBase) {
deskHeight = extractBase;
deskWidth = srcWidth * deskHeight / srcHeight;
} else {
deskWidth = extractBase;
deskHeight = srcHeight * deskWidth / srcWidth;
}
}
} else {
deskHeight = srcHeight;
deskWidth = srcWidth;
}
BufferedImage tag = new BufferedImage (deskWidth, deskHeight, BufferedImage.TYPE_3BYTE_BGR);
tag.getGraphics().drawImage(src.getScaledInstance(deskWidth, deskHeight, Image.SCALE_SMOOTH), 0, 0, null); // tag.getGraphics().drawImage(src.getScaledInstance(widthdist, heightdist, Image.SCALE_AREA_AVERAGING), 0, 0, null);
FileOutputStream deskImage = new FileOutputStream (destURL); /
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder (deskImage);
encoder.encode (tag);
deskImage.close ();
}
红色部分注明的两种方法压缩出来的图片文件较小,且清晰