packagecom.project.video.controller;importjava.awt.Color;importjava.awt.Graphics;importjava.awt.Image;importjava.awt.image.BufferedImage;importjava.io.File;importjava.io.IOException;importjava.util.Arrays;importjavax.imageio.ImageIO;importorg.apache.log4j.Logger;importorg.springframework.web.multipart.MultipartFile;public classImageOp {public static String DEFAULT_PREVFIX = "thumb_";public static Boolean DEFAULT_FORCE = false;//建议该值为false
private static Logger loger = Logger.getLogger(ImageOp.class);/***
Title: thumbnailImage
*@paramimagePath 原图片路径
*@paramw 缩略图宽
*@paramh 缩略图高
*@paramprevfix 生成缩略图的前缀
*@paramforce 是否强制按照宽高生成缩略图(如果为false,则生成最佳比例缩略图)*/
public static void thumbnailImage(MultipartFile imagePath, int w, int h, String prevfix, booleanforce){//File imgFile = new File(imagePath);
try{
loger.info("start .......");//ImageIO 支持的图片类型 : [BMP, bmp, jpg, JPG, wbmp, jpeg, png, PNG, JPEG, WBMP, GIF, gif]
String types =Arrays.toString(ImageIO.getReaderFormatNames());
String suffix= null;//获取图片后缀
loger.info("图片名称"+imagePath.getOriginalFilename());if(imagePath.getOriginalFilename().indexOf(".") > -1) {
suffix= imagePath.getOriginalFilename().substring(imagePath.getOriginalFilename().lastIndexOf(".") + 1);
}//类型和图片后缀全部小写,然后判断后缀是否合法
if(suffix == null || types.toLowerCase().indexOf(suffix.toLowerCase()) < 0){
loger.error("图片后缀不合法");return;
}//获取原图的输入流
BufferedImage img =ImageIO.read(imagePath.getInputStream());if(!force){//根据原图与要求的缩略图比例,找到最合适的缩略图比例
int width = img.getWidth(null);int height = img.getHeight(null);if((width*1.0)/w < (height*1.0)/h){if(width >w){
h= Integer.parseInt(new java.text.DecimalFormat("0").format(height * w/(width*1.0)));
}
}else{if(height >h){
w= Integer.parseInt(new java.text.DecimalFormat("0").format(width * h/(height*1.0)));
}
}
}
BufferedImage bi= newBufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics g=bi.getGraphics();
g.drawImage(img,0, 0, w, h, Color.LIGHT_GRAY, null);
g.dispose();
loger.info("图片生成");
String desc="f:\\12345.jpg";//将图片保存在原目录并加上前缀
ImageIO.write(bi, suffix, newFile(desc));
}catch(Exception e) {
e.printStackTrace();
loger.error("图片生成错误");
}
}
}