@ApiOperation(value = "相机,上传图片")
@RequestMapping(value = "/spvsScheduleAssessContent/upload", method = RequestMethod.POST)
public Map upload(MultipartRequest multipartRequest,@RequestParam(value="image",required=false) String[] image, @RequestParam("myfile") MultipartFile[] myfile, HttpServletRequest request, HttpServletResponse response) {
try {
Map<String, String[]> map=request.getParameterMap();
String uploadPath = request.getServletContext().getRealPath("/")+"images/upload";
if(map!=null){
System.out.println(map);
if(myfile!=null){
String url = MobileFileUploadUtil.filesByReturn(myfile,uploadPath);
if(url==null&&image==null){
return this.resultData("01","请上传图片再提交");
}
if(image!=null){
String str= StringUtils.join(image,",");
if(url==null){
url=str;
}else{
url=url+","+str;
}
}
mobileSpvsScheduleAssessContentService.updatePhotoRemark(map.get("id")[0].toString(),map.get("comment")[0].toString(),url);
}else if(myfile==null&&image!=null){
String url ="";
if(image!=null){
String str= StringUtils.join(image,",");
url=str;
}
mobileSpvsScheduleAssessContentService.updatePhotoRemark(map.get("id")[0].toString(),map.get("comment")[0].toString(),url);
}else{
return this.resultData("01","请上传图片再提交");
}
}
} catch (Exception e) {
e.printStackTrace();
return this.resultData("01");
}
return this.resultData("00");
}

public static String filesByReturn(MultipartFile[] files, String path) throws IOException{
String imgUrl = "";
if (files != null && files.length > 0) {
// 循环获取file数组中得文件
File tempFile;
for (int i = 0; i < files.length; i++) {
MultipartFile file = files[i];

// 保存文件
if (!file.isEmpty()) {
/*String fileName = file.getOriginalFilename();
String newName = System.nanoTime()+ fileName.substring(fileName.lastIndexOf("."), fileName.length());
InputStream input=file.getInputStream();
String prefix = !StringUtils.isEmpty(file.getOriginalFilename()) && file.getOriginalFilename().contains(".")? file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1) : null;
prefix = StringUtils.isEmpty(prefix) ? "png" : prefix;
if (input.available() > 100 * 1024) {
input = zipImageFile(input, prefix);
}
int index;
byte[] bytes = new byte[1024];
FileOutputStream downloadFile = new FileOutputStream(path+"/"+newName);
while ((index = input.read(bytes)) != -1) {
downloadFile.write(bytes, 0, index);
downloadFile.flush();
}
downloadFile.close();
input.close();
imgUrl += "images/upload/" + newName + ",";*/

//方法1
try {
String fileName = file.getOriginalFilename();
String newName = System.nanoTime()+ fileName.substring(fileName.lastIndexOf("."), fileName.length());
File newFile = new File(path+"/"+newName);
//0.5在linux下的/usr/,0,3在windows下的盘符
//String physicalPath = System.getProperty("user.dir").substring(0, 5);
//存储图片临时路径做为调整尺寸用 目录随便用
//String physicalPath = "E:/";
String physicalPath = "/usr/";
tempFile = new File(physicalPath, fileName);
//存储图片
file.transferTo(tempFile);
if (!newFile.getParentFile().exists()) {
newFile.getParentFile().mkdirs();
}
//根据临时图片调整尺寸并存到图片目录下
MobileImageCompressUtil.resize(new File(physicalPath+fileName), newFile, 300, 0.7f);
imgUrl += "images/upload/" + newName + ",";
tempFile.delete();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
if (imgUrl.length() == 0) {
return null;
}
return imgUrl.substring(0, imgUrl.length() - 1);
}


package com.hkl.deliver.cloud.mobile.util;

import javax.imageio.*;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.stream.ImageOutputStream;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;
import java.io.*;


public class MobileImageCompressUtil {

/**
* 高清缩放图片(压缩图片质量,改变图片尺寸,不失真) 若原图宽度小于新宽度,则宽度不变!
* @param newWidth 新的宽度
* @param quality 图片质量参数 0.6f 相当于60%质量
* @param smallIcon 小图添加的后缀和大图区分
*/
public static void resize(File originalFile, File resizedFile, int newWidth, float quality) throws IOException {
ImageWriter imageWriter=null;
ImageOutputStream ios=null;
FileOutputStream out = null;
try {
if (quality > 1) {
throw new IllegalArgumentException("质量参数必须0到1之间");
}

ImageIcon ii = new ImageIcon(originalFile.getCanonicalPath());
Image i = ii.getImage();
Image resizedImage = null;

int iWidth = i.getWidth(null);
int iHeight = i.getHeight(null);

if (iWidth < newWidth) {
newWidth = iWidth;
resizedImage = i.getScaledInstance(iWidth,iHeight, Image.SCALE_SMOOTH);
}else{
if (iWidth > iHeight) {
resizedImage = i.getScaledInstance(newWidth, (newWidth * iHeight) / iWidth, Image.SCALE_SMOOTH);
} else {
resizedImage = i.getScaledInstance((newWidth * iWidth) / iHeight, newWidth, Image.SCALE_SMOOTH);
}
}

Image temp = new ImageIcon(resizedImage).getImage();
BufferedImage bufferedImage = new BufferedImage(temp.getWidth(null), temp.getHeight(null), BufferedImage.TYPE_INT_RGB);
Graphics g = bufferedImage.createGraphics();
g.setColor(Color.white);
g.fillRect(0, 0, temp.getWidth(null), temp.getHeight(null));
g.drawImage(temp, 0, 0, null);
g.dispose();
float softenFactor = 0.05f;
float[] softenArray = { 0, softenFactor, 0, softenFactor, 1 - (softenFactor * 4), softenFactor, 0, softenFactor, 0 };
Kernel kernel = new Kernel(3, 3, softenArray);
ConvolveOp cOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
bufferedImage = cOp.filter(bufferedImage, null);
out = new FileOutputStream(resizedFile);
imageWriter = ImageIO.getImageWritersBySuffix("jpg").next();
ios = ImageIO.createImageOutputStream(out);
imageWriter.setOutput(ios);
// and metadata
IIOMetadata imageMetaData = imageWriter.getDefaultImageMetadata(
new ImageTypeSpecifier(bufferedImage), null);
ImageWriteParam imgParams = imageWriter.getDefaultWriteParam();
imgParams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
imgParams.setCompressionQuality(quality);
imageWriter.write(imageMetaData,new IIOImage(bufferedImage, null, null), null);
ios.flush();
out.flush();
bufferedImage.flush();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
ios.close();
out.close();
imageWriter.dispose();
} catch (IOException e) {
e.printStackTrace();
}

}
}
/**
* 遍历文件夹修改图片增加缩略图
* @param path 需要遍历的文件夹
* @throws IOException
*/
public static void traverseFolder(String path) throws IOException {

File file = new File(path);
if (file.exists()) {
File[] files = file.listFiles();
if (files.length == 0) {
System.out.println("文件夹是空的!");
return;
} else {
for (File file2 : files) {
if (file2.isDirectory()) {
System.out.println("文件夹:" + file2.getAbsolutePath());
traverseFolder(file2.getAbsolutePath());
} else {
System.out.println("文件:" + file2.getAbsolutePath());
File originalImage = new File(file2.getAbsolutePath());
String path2 = file2.getAbsolutePath().substring(0,file2.getAbsolutePath().lastIndexOf("."));
File resizedImg1 = new File(path2);
resize(originalImage, resizedImg1, 1920, 0.7f);
File resizedImg2 = new File(path2+"small");
resize(originalImage, resizedImg2, 300, 1f);
//originalImage.delete();
}
}
}
} else {
System.out.println("文件不存在!");
}
}

// 压缩图片
public static InputStream zipImageFile(InputStream picInput, String prefix) throws IOException {
// 原图
BufferedImage orginPic = ImageIO.read(picInput);
int picWidth = orginPic.getWidth();
int picHight = orginPic.getHeight();

// 压缩
BufferedImage result = new BufferedImage(picWidth, picHight, BufferedImage.TYPE_INT_RGB);
Image scaledInstance = orginPic.getScaledInstance(picWidth, picHight, Image.SCALE_SMOOTH);
Graphics2D g = result.createGraphics();
g.drawImage(scaledInstance, 0, 0, null);
g.dispose();
ByteArrayOutputStream bs = new ByteArrayOutputStream();
ImageIO.write(result, prefix, bs);
scaledInstance.flush();
result.flush();
return new ByteArrayInputStream(bs.toByteArray());
}

}
posted on 2019-08-29 14:56  一抹书香  阅读(416)  评论(0编辑  收藏  举报