上传图片的方法
@ResponseBody
@RequestMapping(value="/upload_images_rich/{fileKind}")
public Object upload_images_rich(@RequestParam MultipartFile file,@PathVariable("fileKind") String fileKind) {
JsonResult<Map<String,Object>> result = new JsonResult<Map<String,Object>>().successMsg();
try{
UploaderFileUtil fileUtil = new UploaderFileUtil(file);
//保存原图 缩略图 浏览图
UploaderFileBean uploaderFileBean = fileUtil.saveImageOriginal("images", fileKind);
String thumbURL = fileUtil.saveImageThumb(uploaderFileBean.getOriginalURL(),"images", fileKind,uploaderFileBean.getFileName());
String browseURL = fileUtil.saveImageBrowse(uploaderFileBean.getOriginalURL(),"images", fileKind,uploaderFileBean.getFileName());
Map<String,Object> map = new HashMap<>();
map.put("src",Const.digitPath + "/" + browseURL);//此处必须给定绝对路径
result.setCode(0);
result.setData(map);
return result;
}catch (Exception e){
return result.errorMsg();
}
}
UploaderFileUtil工具类
package com.wonders.framework.util;
import com.drew.imaging.jpeg.JpegMetadataReader;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.Tag;
import com.drew.metadata.exif.ExifIFD0Directory;
import com.drew.metadata.exif.ExifSubIFDDirectory;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.wonders.framework.util.bean.ImageFileBean;
import com.wonders.framework.util.bean.UploaderFileBean;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.FileImageInputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
/**
* Created by IntelliJ IDEA.
* User:ZJX
* Date:2020/01/09
* Time:15:53
* To change this template use File|Settings|File Templates.
* tif 需要三个包 jai_core.jar jai_imageio-1.1.jar jai_codec.jar
**/
public class UploaderFileUtil {
private MultipartFile mfile;
public UploaderFileUtil() {
}
public UploaderFileUtil(MultipartFile mfile) {
this.mfile = mfile;
}
/**
* 保存图片为 缩率图
*
* @param originalURL 源文件路径
* @param storePath 文件存储文件夹
* @param myFolderName 文件存储子文件夹
* @param originName 文件名字
* @param fileSuffix 文件后缀 根据文件后缀,判断不同的文件处理 tif 和 tiff 为tif处理方式(tif会压缩为 jpg 的图片) 或其他的图片格式。
* @return 生成缩率图的存储路径
*/
public String saveImageThumb(String originalURL, String storePath, String myFolderName, String originName, String fileSuffix) {
fileSuffix = fileSuffix.toLowerCase();
if ("tif".equals(fileSuffix) || "tiff".equals(fileSuffix)) {
return this.saveTifToJpgThumb(originalURL, storePath, myFolderName, originName);
} else {
return this.saveImageThumb(originalURL, storePath, myFolderName, originName);
}
}
/**
* 普通图片处理为缩率图
*
* @param originalURL 源文件路径
* @param storePath 文件存储文件夹
* @param myFolderName 文件存储子文件夹
* @param originName 文件名字
* @return 生成缩率图的存储路径
*/
public String saveImageThumb(String originalURL, String storePath, String myFolderName, String originName) {
String thumbURL = "default_image.png";
try {
BufferedImage originalImage = ImageIO.read(new File(Const.uploadFilePath + "/" + originalURL));
thumbURL = this.createImageThumb(storePath, myFolderName, originName, originalImage);
} catch (IOException e) {
e.printStackTrace();
}
return thumbURL;
}
/**
* tif 图片处理为缩率图 jpg 格式。
*
* @param originalURL 源文件路径
* @param storePath 文件存储文件夹
* @param myFolderName 文件存储子文件夹
* @param originName 文件名字
* @return 生成缩率图的存储路径
*/
public String saveTifToJpgThumb(String originalURL, String storePath, String myFolderName, String originName) {
originName = originName.substring(0, originName.lastIndexOf(".")) + ".jpg";
String thumbURL = "default_image.png";
ImageReader reader = null;
FileImageInputStream inputStream = null;
try {
reader = ImageIO.getImageReadersByFormatName("tiff").next();
inputStream = new FileImageInputStream(new File(Const.uploadFilePath + "/" + originalURL));
reader.setInput(inputStream);
BufferedImage originalImage = reader.read(0);
thumbURL = this.createImageThumb(storePath, myFolderName, originName, originalImage);
} catch (IOException e) {
e.printStackTrace();
}
return thumbURL;
}
/**
* 创建缩率图
*/
private String createImageThumb(String storePath, String myFolderName, String originName, BufferedImage originalImage) throws IOException {
String save_path = Const.uploadFilePath + "\\" + storePath + "\\" + Const.folder_thumb + "\\" + myFolderName;
File save_file_url = new File(save_path);
//文件夹不存在
if (!save_file_url.exists()) {
save_file_url.mkdirs();
}
int w = originalImage.getWidth(null);
int h = originalImage.getHeight(null);
int new_w = 0;
int new_h = 0;
if (w <= Const.thumb_widht) {
new_w = w;
new_h = h;
} else {
if (w >= h) {
if (w > Const.thumb_widht) {
new_w = Const.thumb_widht;
new_h = h * Const.thumb_widht / w;
}
if (new_h > Const.thumb_height) {
new_w = new_w * Const.thumb_height / new_h;
new_h = Const.thumb_height;
}
} else {
new_h = Const.thumb_height;
new_w = w * Const.thumb_height / h;
}
}
BufferedImage image = new BufferedImage(new_w, new_h, BufferedImage.TYPE_3BYTE_BGR);
image.getGraphics().drawImage(originalImage.getScaledInstance(new_w, new_h, Image.SCALE_SMOOTH), 0, 0, null);
OutputStream os = new FileOutputStream(save_path + "\\" + originName);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
encoder.encode(image);
String thumbURL = storePath + "/" + Const.folder_thumb + "/" + myFolderName + "/" + originName;
os.flush();
os.close();
return thumbURL;
}
/**
* 保存图片为 浏览图
*
* @param originalURL 源文件路径
* @param storePath 文件存储文件夹
* @param myFolderName 文件存储子文件夹
* @param originName 文件名字
* @param fileSuffix 文件后缀 根据文件后缀,判断不同的文件处理 tif 和 tiff 为tif处理方式(tif会压缩为 jpg 的图片) 或其他的图片格式。
* @return 生成浏览图的存储路径
*/
public String saveImageBrowse(String originalURL, String storePath, String myFolderName, String originName, String fileSuffix) {
fileSuffix = fileSuffix.toLowerCase();
if ("tif".equals(fileSuffix) || "tiff".equals(fileSuffix)) {
return this.saveTifToJpgBrowse(originalURL, storePath, myFolderName, originName);
} else {
return this.saveImageBrowse(originalURL, storePath, myFolderName, originName);
}
}
/**
* 普通图片处理为 浏览图
*
* @param originalURL 源文件路径
* @param storePath 文件存储文件夹
* @param myFolderName 文件存储子文件夹
* @param originName 文件名字
* @return 生成 浏览图的存储路径
*/
public String saveImageBrowse(String originalURL, String storePath, String myFolderName, String originName) {
String browseURL = "default_image.png";
try {
BufferedImage originalImage = ImageIO.read(new File(Const.uploadFilePath + "/" + originalURL));
browseURL = this.createImageBrowse(storePath, myFolderName, originName, originalImage);
} catch (IOException e) {
e.printStackTrace();
}
return browseURL;
}
/**
* tif 图片处理为浏览图 jpg 格式。
*
* @param originalURL 源文件路径
* @param storePath 文件存储文件夹
* @param myFolderName 文件存储子文件夹
* @param originName 文件名字
* @return 生成浏览图的存储路径
*/
public String saveTifToJpgBrowse(String originalURL, String storePath, String myFolderName, String originName) {
originName = originName.substring(0, originName.lastIndexOf(".")) + ".jpg";
String browseURL = "default_image.png";
ImageReader reader = null;
FileImageInputStream inputStream = null;
try {
reader = ImageIO.getImageReadersByFormatName("tiff").next();
inputStream = new FileImageInputStream(new File(Const.uploadFilePath + "/" + originalURL));
reader.setInput(inputStream);
BufferedImage originalImage = reader.read(0);
browseURL = this.createImageBrowse(storePath, myFolderName, originName, originalImage);
} catch (IOException e) {
e.printStackTrace();
}
return browseURL;
}
private String createImageBrowse(String storePath, String myFolderName, String originName, BufferedImage originalImage) throws IOException {
String save_path = Const.uploadFilePath + "\\" + storePath + "\\" + Const.folder_browse + "\\" + myFolderName;
File save_file_url = new File(save_path);
//文件夹不存在
if (!save_file_url.exists()) {
save_file_url.mkdirs();
}
int w = originalImage.getWidth(null);
int h = originalImage.getHeight(null);
int new_w = 0;
int new_h = 0;
if (w <= Const.browse_widht) {
new_w = w;
new_h = h;
} else {
if (w >= h) {
if (w > Const.browse_widht) {
new_w = Const.browse_widht;
new_h = h * Const.browse_widht / w;
}
if (new_h > Const.browse_height) {
new_w = new_w * Const.browse_height / new_h;
new_h = Const.browse_height;
}
} else {
new_h = Const.browse_height;
new_w = w * Const.browse_height / h;
}
}
BufferedImage image = new BufferedImage(new_w, new_h, BufferedImage.TYPE_3BYTE_BGR);
image.getGraphics().drawImage(originalImage.getScaledInstance(new_w, new_h, Image.SCALE_SMOOTH), 0, 0, null);
OutputStream os = new FileOutputStream(save_path + "\\" + originName);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
encoder.encode(image);
String browseURL = storePath + "/" + Const.folder_browse + "/" + myFolderName + "/" + originName;
os.flush();
os.close();
return browseURL;
}
/**
* 保存原图 到服务器上。
*
* @param storePath
* @param myFolderName
* @return
* @throws IOException
*/
public UploaderFileBean saveImageOriginal(String storePath, String myFolderName) throws IOException {
String save_path = Const.uploadFilePath + "\\" + storePath + "\\" + Const.folder_original + "\\" + myFolderName;
UploaderFileBean uploadBean = new UploaderFileBean();
File save_file_url = new File(save_path);
//文件夹不存在
if (!save_file_url.exists()) {
save_file_url.mkdirs();
}
String originName = mfile.getOriginalFilename();
String titleName = originName.substring(0, originName.lastIndexOf("."));
long fileSize = mfile.getSize();
originName = System.currentTimeMillis() + "_" + originName;
String saveURL = storePath + "/" + Const.folder_original + "/" + myFolderName + "/" + originName;
File file = new File(save_path, originName);
mfile.transferTo(file);//上传源文件
uploadBean.setOriginalURL(saveURL);
uploadBean.setTitleName(titleName);
uploadBean.setFileName(originName);
uploadBean.setFileSize(fileSize);
ImageFileBean imageInfo = this.getImageOriginalInfo(file);
uploadBean.setImageInfo(imageInfo);
return uploadBean;
}
public ImageFileBean getImageOriginalInfo(File file) {
ImageFileBean imageBean = new ImageFileBean();
Metadata metadata = null;
Directory exif = null;
String description = null;
try {
metadata = JpegMetadataReader.readMetadata(file);
exif = metadata.getDirectory(ExifIFD0Directory.class);
if (exif != null) {
for (Tag tag : exif.getTags()) {
description = tag.getDescription();
switch (tag.getTagType()) {
case ExifIFD0Directory.TAG_MAKE:
imageBean.setMymake(description);
case ExifIFD0Directory.TAG_MODEL:
imageBean.setMymodel(description);
case ExifIFD0Directory.TAG_ORIENTATION:
imageBean.setMyorientation(description);
case ExifIFD0Directory.TAG_X_RESOLUTION:
imageBean.setMyxResolution(description);
case ExifIFD0Directory.TAG_Y_RESOLUTION:
imageBean.setMyyResolution(description);
case ExifIFD0Directory.TAG_RESOLUTION_UNIT:
imageBean.setMyresolutionUnit(description);
default:
;
}
}
}
exif = metadata.getDirectory(ExifSubIFDDirectory.class);
if (exif != null) {
for (Tag tag : exif.getTags()) {
description = tag.getDescription();
switch (tag.getTagType()) {
case ExifSubIFDDirectory.TAG_EXPOSURE_TIME:
imageBean.setMyexposureTime(description);
case ExifSubIFDDirectory.TAG_FNUMBER:
imageBean.setMyfNumber(description);
case ExifSubIFDDirectory.TAG_EXPOSURE_PROGRAM:
imageBean.setMyexposureProgram(description);
case ExifSubIFDDirectory.TAG_ISO_EQUIVALENT:
imageBean.setMyisoSpeedRatings(description);
case ExifSubIFDDirectory.TAG_EXIF_VERSION:
imageBean.setMyexifVersion(description);
case ExifSubIFDDirectory.TAG_DATETIME_ORIGINAL:
imageBean.setMyoriginalDate(description);
case ExifSubIFDDirectory.TAG_SHUTTER_SPEED:
imageBean.setMyshutterSpeed(description);
case ExifSubIFDDirectory.TAG_APERTURE:
imageBean.setMyoriginalDate(description);
case ExifSubIFDDirectory.TAG_BRIGHTNESS_VALUE:
imageBean.setMybrightness(description);
case ExifSubIFDDirectory.TAG_EXPOSURE_BIAS:
imageBean.setMyexposureBias(description);
case ExifSubIFDDirectory.TAG_MAX_APERTURE:
imageBean.setMymaxAperture(description);
case ExifSubIFDDirectory.TAG_METERING_MODE:
imageBean.setMymeteringMode(description);
case ExifSubIFDDirectory.TAG_FLASH:
imageBean.setMyflash(description);
case ExifSubIFDDirectory.TAG_FOCAL_LENGTH:
imageBean.setMyfocalLength(description);
case ExifSubIFDDirectory.TAG_FLASHPIX_VERSION:
imageBean.setMyflashPixVersion(description);
case ExifSubIFDDirectory.TAG_COLOR_SPACE:
imageBean.setMycolorSpace(description);
case ExifSubIFDDirectory.TAG_EXIF_IMAGE_WIDTH:
imageBean.setMywidth(description.replace("pixels", "").trim());
case ExifSubIFDDirectory.TAG_EXIF_IMAGE_HEIGHT:
imageBean.setMyheight(description.replace("pixels", "").trim());
case ExifSubIFDDirectory.TAG_EXPOSURE_MODE:
imageBean.setMyexposureMode(description);
case ExifSubIFDDirectory.TAG_WHITE_BALANCE_MODE:
imageBean.setMywhiteBalanceMode(description);
case ExifSubIFDDirectory.TAG_SCENE_CAPTURE_TYPE:
imageBean.setMysceneCaptureType(description);
default:
}
}
}
return imageBean;
} catch (NoSuchMethodError e) {
// e.printStackTrace();
return null;
} catch (Exception e) {
// e.printStackTrace();
return null;
}
}
public UploaderFileBean saveImageOrgimg(String storePath, String myFolderName) throws IOException {
String save_path = Const.uploadFilePath + "\\" + storePath + "\\" + Const.folder_orgimg + "\\" + myFolderName;
UploaderFileBean uploadBean = new UploaderFileBean();
File save_file_url = new File(save_path);
//文件夹不存在
if (!save_file_url.exists()) {
save_file_url.mkdirs();
}
String originName = mfile.getOriginalFilename();
originName = System.currentTimeMillis() + originName;
String saveURL = storePath + "/" + Const.folder_orgimg + "/" + myFolderName + "/" + originName;
File file = new File(save_path, originName);
mfile.transferTo(file);//上传源文件
uploadBean.setOrgimgURL(saveURL);
uploadBean.setFileName(originName);
return uploadBean;
}
/**
* @param storePath Const.file_store_map 对应的值
* @param folderPath browse 或 original
* @param myFolderName
* @return
*/
public UploaderFileBean saveFile(String storePath, String folderPath, String myFolderName) {
UploaderFileBean uploadBean = new UploaderFileBean();
String save_path = Const.uploadFilePath + "\\" + storePath + "\\" + folderPath + "\\" + myFolderName;
File save_file_url = new File(save_path);
//文件夹不存在
if (!save_file_url.exists()) {
save_file_url.mkdirs();
}
String originName = mfile.getOriginalFilename();
String titleName = originName.substring(0, originName.lastIndexOf("."));
originName = System.currentTimeMillis() + originName;
long fileSize = mfile.getSize();
String saveURL = storePath + "/" + folderPath + "/" + myFolderName + "/" + originName;
try {
File file = new File(save_path, originName);
mfile.transferTo(file);//上传源文件
uploadBean.setOriginalURL(saveURL);
uploadBean.setTitleName(titleName);
uploadBean.setFileName(originName);
uploadBean.setFileSize(fileSize);
} catch (IOException e) {
e.printStackTrace();
}
return uploadBean;
}
/**
* @param folderPath browse 或 original
* @return
*/
public UploaderFileBean saveFile(String folderPath) {
UploaderFileBean uploadBean = new UploaderFileBean();
String save_path = Const.uploadFilePath + "\\" + folderPath;
File save_file_url = new File(save_path);
//文件夹不存在
if (!save_file_url.exists()) {
save_file_url.mkdirs();
}
String originName = mfile.getOriginalFilename();
String save_originName = System.currentTimeMillis() + "_" + originName;
long fileSize = mfile.getSize();
String saveURL = folderPath + "/" + save_originName;
try {
File file = new File(save_path, save_originName);
mfile.transferTo(file);//上传源文件
uploadBean.setOriginalURL(saveURL);
uploadBean.setFileName(originName);
uploadBean.setFileSize(fileSize);
} catch (IOException e) {
e.printStackTrace();
}
return uploadBean;
}
public static void main(String[] args) {
UploaderFileUtil fileUtil = new UploaderFileUtil();
String originalURL, storePath, myFolderName, originName;
originalURL = "image/original/win8桌面5/1587891826963_00001535.jpg";
storePath = "image";
myFolderName = "win8桌面5";
originName = "1587891826963_00001535.jpg";
String fileSuffix = originName.substring(originName.lastIndexOf(".") + 1);
fileUtil.saveImageThumb(originalURL, storePath, myFolderName, originName, fileSuffix);
fileUtil.saveImageBrowse(originalURL, storePath, myFolderName, originName, fileSuffix);
}
}
UploaderFileBean
package com.wonders.framework.util.bean;
import java.io.File;
import java.text.DecimalFormat;
import java.util.Map;
/**
* Created by IntelliJ IDEA.
* User:ZJX
* Date:2020/01/09
* Time:15:52
* To change this template use File|Settings|File Templates.
**/
public class UploaderFileBean {
private String titleName; //源文件名
private String fileName; //文件名 带后缀
private String originalURL; //源文件存储路径
private String browseURL;//浏览文件存储路径
private String thumbURL;//缩略图存储路径
private String orgimgURL;// 缩略图的原图 非 图片文件 存储路径
private String fileSuffix; //后缀
private long fileSize; //文件大小
private String fileSize1; //通过 fileSize 格式化后的fileSize
private String fileSizeUnit; //通过 fileSize 格式化后的fileSize 的单位
private int videoDuration; //上传视频的视频长度
private String themeType; // 文件类型 图片 文件 视频 等
private ImageFileBean imageInfo;
public String getTitleName() {
return titleName;
}
public void setTitleName(String titleName) {
this.titleName = titleName;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getOriginalURL() {
return originalURL;
}
public void setOriginalURL(String originalURL) {
this.originalURL = originalURL;
}
public String getBrowseURL() {
return browseURL;
}
public void setBrowseURL(String browseURL) {
this.browseURL = browseURL;
}
public String getThumbURL() {
return thumbURL;
}
public void setThumbURL(String thumbURL) {
this.thumbURL = thumbURL;
}
public String getOrgimgURL() {
return orgimgURL;
}
public void setOrgimgURL(String orgimgURL) {
this.orgimgURL = orgimgURL;
}
public String getFileSuffix() {
return fileSuffix;
}
public void setFileSuffix(String fileSuffix) {
this.fileSuffix = fileSuffix;
}
public long getFileSize() {
return fileSize;
}
public void setFileSize(long fileSize) {
this.fileSize = fileSize;
if (fileSize < 1024) {
this.fileSize1 = "1";
this.fileSizeUnit = "KB";
} else {
DecimalFormat decimalFormat2 = new DecimalFormat();
decimalFormat2.applyPattern("#.#");
float temp = fileSize / 1024f;
if (temp < 1024) {
this.fileSize1 = decimalFormat2.format(temp);
this.fileSizeUnit = "KB";
} else {
temp = temp / 1024f;
if (temp < 1024) {
this.fileSize1 = decimalFormat2.format(temp);
this.fileSizeUnit = "MB";
} else {
temp = temp / 1024f;
this.fileSize1 = decimalFormat2.format(temp);
this.fileSizeUnit = "GB";
}
}
}
}
public String getFileSize1() {
return fileSize1;
}
public String getFileSizeUnit() {
return fileSizeUnit;
}
public String getThemeType() {
return themeType;
}
public void setThemeType(String themeType) {
this.themeType = themeType;
}
public ImageFileBean getImageInfo() {
return imageInfo;
}
public void setImageInfo(ImageFileBean imageInfo) {
this.imageInfo = imageInfo;
}
public int getVideoDuration() {
return videoDuration;
}
public void setVideoDuration(int videoDuration) {
this.videoDuration = videoDuration;
}
}
Const
package com.wonders.framework.util;
import java.util.HashMap;
import java.util.Map;
public class Const {
public static String ROOT_DIR = "E:\\CodeSpace\项目\\WebRoot";
public final static String SESSION_USER_INFO = "session_user_info";
public final static String SESSION_BATCH_FILE = "session_batch_file";
public static String ctxPath;
public static String uploadFilePath = "E:\\Artifacts_Home\xxx_war_exploded\\digit_files";
public static String downloadTempFilePath = "download_temp";
public static String BATCH_FOLDER_DIR = "D:/Temp/rootFolder";
public static String digitPath;
public static Map<String, String> file_store_map = new HashMap<>();
public static Map<String, String> operation_file_map = new HashMap<>();
public static String folder_thumb = "thumb"; //缩略图
public static int thumb_widht = 480; //缩略图宽
public static int thumb_height = 320; //缩略图高
public static String folder_browse = "browse";//浏览文件
public static int browse_widht = 800; //缩略图宽
public static int browse_height = 600; //缩略图高
public static String folder_original = "original";//源文件
public static String folder_orgimg = "orgimg";//缩略图的原图 非 图片文件 上传图片使用
static {
file_store_map.put("tx", "image");
file_store_map.put("ys", "media");
file_store_map.put("wx", "document");
file_store_map.put("cb", "publication");
file_store_map.put("3d", "in3D");
operation_file_map.put("tx", "jpg_tif_tiff_png_gif_bmp");
operation_file_map.put("ys", "mp4_mp3");
operation_file_map.put("wx", "all");
operation_file_map.put("cb", "all");
operation_file_map.put("3d", "all");
}
}
谢谢!!