importcom.sun.image.codec.jpeg.JPEGCodec;importcom.sun.image.codec.jpeg.JPEGEncodeParam;importcom.sun.image.codec.jpeg.JPEGImageEncoder;importorg.apache.commons.lang3.StringUtils;importjavax.imageio.ImageIO;importjava.awt.image.BufferedImage;importjava.io.File;importjava.io.FileOutputStream;importjava.io.IOException;importjava.util.HashMap;importjava.util.Map;public classImageUtil2 {
private BufferedImage zoomImage(BufferedImage im, int toWidth, inttoHeight) {
BufferedImage result= newBufferedImage(toWidth, toHeight, BufferedImage.TYPE_INT_RGB);
result.getGraphics().drawImage(im.getScaledInstance(toWidth, toHeight, java.awt.Image.SCALE_SMOOTH),0, 0, null);returnresult;
}
privateBufferedImage getImageList(String ImgList, String[] type) {
Map map = new HashMap<>();for(String s : type) {
map.put(s,true);
}
BufferedImage imageList= null;
File file= newFile(ImgList);try{if (file.length() != 0 && map.get(getExtension(file.getName())) != null) {
imageList=javax.imageio.ImageIO.read(file);
}
}catch(Exception e) {
System.out.println(e.getMessage());
}returnimageList;
}
public boolean writeToDisk(BufferedImage im, String path, String fileName) throwsIOException {
File f= new File(path +fileName);
String fileType=getExtension(fileName);if(StringUtils.isNotEmpty(fileType)) {
ImageIO.write(im, fileType, f);
im.flush();return true;
}return false;
}
private booleanwriteHighQuality(String path, BufferedImage im, String fileFullPath) {
FileOutputStream newImageStream;try{//输出到文件流
newImageStream = new FileOutputStream(fileFullPath +path);
JPEGImageEncoder encoder=JPEGCodec.createJPEGEncoder(newImageStream);
JPEGEncodeParam jep=JPEGCodec.getDefaultJPEGEncodeParam(im);//压缩质量
jep.setQuality(1f, true);
encoder.encode(im, jep);//近JPEG编码
newImageStream.close();
}catch(Exception e) {return false;
}return true;
}
privateString getExtension(String fileName) {try{return fileName.split("\\.")[fileName.split("\\.").length - 1];
}catch(Exception e) {return null;
}
}public static voidmain(String[] args) {//windows路径,linux环境下相应修改
String outputFolder = "D:\\test\\";
String fileName= "D:\\test\\test.jpg";
ImageUtil2 r= newImageUtil2();int toWidth = 220, toHeight = 220;
BufferedImage imageList= r.getImageList(fileName, new String[]{"jpg", "png", "gif"});
r.writeHighQuality("newFile.jpg", r.zoomImage(imageList, toWidth, toHeight), outputFolder);
}
}