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;
}/*** 把图片写到磁盘上
*@parampath 图片写入的文件夹地址
*@paramfileName 写入图片的名字*/
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;
}/*** 取文件名的后缀
*@paramfileName 格式如:cn1100000213EA_1_xnl.jpg
* @date 2020-08-13*/
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);
}
}