public class ImageCompressUtil {
public static void reduceImg(String imgsrc, String imgdist) {
try {
File srcfile = new File(imgsrc);
if (!srcfile.exists()) {
System.out.println("文件不存在");
}
int[] results = getImgWidthHeight(srcfile);
int widthdist = results[0];
int heightdist = results[1];
Image src = ImageIO.read(srcfile);
BufferedImage tag = new BufferedImage( widthdist, heightdist, BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(src.getScaledInstance(widthdist, heightdist, Image.SCALE_SMOOTH), 0, 0, null);
FileOutputStream out = new FileOutputStream(imgdist);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(tag);
out.close();
} catch (Exception ef) {
ef.printStackTrace();
}
}
public static void reduceImg(InputStream imgsrc, String imgdist) throws IOException {
Image src = ImageIO.read(imgsrc);
int[] results = getImgWidthHeight(src);
int widthdist = results[0];
int heightdist = results[1];
BufferedImage tag = new BufferedImage( widthdist, heightdist, BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(src.getScaledInstance(widthdist, heightdist, Image.SCALE_SMOOTH), 0, 0, null);
FileOutputStream out = new FileOutputStream(imgdist);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(tag);
out.close();
imgsrc.close();
}
public static int[] getImgWidthHeight(File file) {
InputStream is = null;
BufferedImage src = null;
int result[] = { 0, 0 };
try {
is = new FileInputStream(file);
src = ImageIO.read(is);
result[0] =src.getWidth(null);
result[1] =src.getHeight(null);
is.close();
} catch (Exception ef) {
ef.printStackTrace();
}
return result;
}
public static int[] getImgWidthHeight(Image image) {
int result[] = { 0, 0 };
try {
result[0] =image.getWidth(null);
result[1] =image.getHeight(null);
} catch (Exception ef) {
ef.printStackTrace();
}
return result;
}
}