H5压缩图片 AJAX上传图片

时间:2021-12-08 19:30:28

HTML5 Canvas压缩图片 AJAX上传图片

Canvas压缩图片

封装压缩图片的js

function compress(event, callback){
//var inputID="file";
var file = event.files[0];
var reader = new FileReader();
reader.onload = function (e) {
var image = $('<img />');
image.on('load', function () {
var canvas = document.createElement('canvas');
var width = this.width;
var height = this.height;

canvas.width = this.width;
canvas.height = this.height;

var context = canvas.getContext('2d');
context.clearRect(0, 0, width, height);

context.drawImage(this, 0, 0, this.width, this.height);
var quality = 0.9;//可以理解为压缩程度
//quality :图片质量。0 到 1 之间的数字,并且只在格式为 image/jpeg 或 image/webp 时才有效,如果参数值格式不合法,将会被忽略并使用默认值
var data ;
var result;
var length;
//处理图片过大问题
//控制图片上传的大小,注意若图片过大 ajax上传的时候会出现参数为null的错误
//这里如果图片过大会将图片压缩程度放大
do{
data= canvas.toDataURL('image/jpeg',quality);//压缩图片
length = data.length;
result = ((length/4)*3+1023)/1024;//计算压缩后图片的大小(单位:KB)
console.log("result:"+result);
quality-=0.05;
}while(result>450);
//data:base64
callback(data);//回调函数
});
image.attr('src', e.target.result);
};
reader.readAsDataURL(file);
}

调用compress方法获取base64图片编码并使用AJAX上传

compress($("#imgID"),function(base64Img){
$.ajax({
type:"POST",
url:$("#basePath").val()+"material/uploadMaterial",
data:{
base64Img : base64Img
},
success:function(data){
var result = eval('(' + data + ')');
if(result =='SUC'){
alert("上传成功");
return false;
}else{
alert("上传失败,请稍后重试");
return false;
}
}
});
});

UploadController.java

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import sun.misc.BASE64Decoder;

@Controller
@RequestMapping(value="/upload")
public class UploadController {

private static final Logger logger = Logger.getLogger(UploadController.class);

@ResponseBody
@RequestMapping("/uploadImg")
public synchronized String uploadImg(String base64Img,
HttpServletRequest request,HttpServletResponse response)
throws IllegalStateException, IOException{
logger.info("uploadMaterial#####图片...");
String imgName;
String imgPath;
imgName=UUID.randomUUID().toString().replace("-", "")+".jpeg";//生成名字
imgPath="/app/mount/imageServer/material/"+imgName;//上传路径
String[] strs=base64Img.split(",");
//System.out.println("base64:"+strs[1]);
try {
String data =savePictoServer(strs[1],imgPath);
logger.info("--->>>图片上传成功!::"+data);
return "SUC";
} catch (Exception e) {
logger.info("uploadMaterial######图片转化异常......");
return "图片上传失败,请稍后重试";
}
}

//图片上传
public static String savePictoServer(String base64String,String path)throws Exception{
BASE64Decoder decoder = new sun.misc.BASE64Decoder();
byte[] bytes1 = decoder.decodeBuffer(base64String);
ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
BufferedImage bi1 =ImageIO.read(bais);

File dir=new File(path);
if(!dir.exists()){
dir.mkdirs();
}
String fileName=path;
File w2 = new File(fileName);//可以是jpg,png,gif格式
ImageIO.write(bi1, "jpg", w2);//不管输出什么格式图片,此处不需改动
return fileName;
}
}

使用到的jar包

catalina-manager.jar、commons-fileupload-1.2.1.jar、commons-io-1.3.2.jar