packagecom.tongyou.util;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;importorg.springframework.util.FileCopyUtils;importorg.springframework.web.multipart.MultipartFile;importjava.awt.Color;importjava.awt.Graphics2D;importjava.awt.image.BufferedImage;importjava.io.File;importjava.io.IOException;importjavax.imageio.ImageIO;/*** 文件上传工具
*@version1.0.0
* @date 2018/4/2 14:00*/
public class UploadUtil implementsRunnable {private static final Logger LOG = LoggerFactory.getLogger(UploadUtil.class);privateMultipartFile multipartFile;/*** 根路径*/
privateString rootPath;/*** 文件夹全路径*/
privateString folderPath;/*** 文件全路径*/
privateString filePath;/*** 文件访问地址*/
privateString fileUrl;publicUploadUtil(MultipartFile multipartFile, String folderName) {this.multipartFile =multipartFile;this.rootPath = "V:/XPH/image";
String realFilename=multipartFile.getOriginalFilename();
String fileExtension= realFilename.substring(realFilename.lastIndexOf("."));
String fileName= UUIDUtil.randomUUID() +fileExtension;this.folderPath = this.rootPath +folderName;this.filePath = folderPath + "/" +fileName;
String fileUrl= "http://192.168.0.148:80" + folderName + "/" +fileName;this.fileUrl = fileUrl.substring(0, fileUrl.lastIndexOf("."));
}private void upload() throwsException {
File dirPath= newFile(folderPath);if (!dirPath.exists()) {
dirPath.mkdirs();
}
File uploadFile= newFile(filePath);
FileCopyUtils.copy(multipartFile.getBytes(), uploadFile);//将上传的图片同一存为jpg格式
this.changJPG(uploadFile);//生成缩略图
this.changSmall(uploadFile);
}private void changJPG(File uploadFile) throwsIOException {
String path=uploadFile.getPath();//TODO Auto-generated method stub
BufferedImage bufferedImage=ImageIO.read(uploadFile);//create a blank, RGB, same width and height, and a white background
BufferedImage newBufferedImage = newBufferedImage(bufferedImage.getWidth(),
bufferedImage.getHeight(), BufferedImage.TYPE_INT_RGB);//TYPE_INT_RGB:创建一个RBG图像,24位深度,成功将32位图转化成24位
newBufferedImage.createGraphics().drawImage(bufferedImage, 0, 0, Color.WHITE, null);//write to jpeg file
String fileName = path.substring(0,path.lastIndexOf("."));
ImageIO.write(newBufferedImage,"jpg", new File(fileName+".jpg"));
}
@Overridepublic voidrun() {try{
upload();
}catch(Exception e) {
LOG.error("文件上传失败:", e);
}
}publicString getFileUrl() {returnfileUrl;
}/*** 将指定图片在指定 位置生成缩略图*/
private voidchangSmall(File uploadFile){
String path=uploadFile.getPath();try{
BufferedImage input=ImageIO.read(uploadFile);
BufferedImage inputbig= new BufferedImage(33, 33, BufferedImage.TYPE_INT_BGR);
Graphics2D g=(Graphics2D) inputbig.getGraphics();
g.drawImage(input,0, 0,33,33,null); //画图
g.dispose();
inputbig.flush();
String fname= path.substring(0, path.lastIndexOf("."));//新名字
String parent =uploadFile.getParent();
ImageIO.write(inputbig,"jpg", new File( fname + "_small.jpg")); //将其保存在C:/imageSort/targetPIC/下
} catch(Exception ex) {
ex.printStackTrace();
}
}
}