图片太大 做压缩上传,可以在前端js压缩上传,也可仪后台 转base64压缩上传;
前端:
总体思路是:1. 使用HTML5的FileReader接口来读取用户上传的图片2. 使用canvas drawImage接口绘制到Canvas 2d中3. 使用canvas toDataUrl接口把图片转成base64编码字符串(这里可以降低图片质量)4. 完成image src的替换后,表单提交时,就提交新的被压缩过的图像
window.onload = function() {
var input = document.getElementById("img_input");
var result = document.getElementById("result");
var img_area = document.getElementById("img_area");
if (typeof(FileReader) === 'undefined') {
result.innerHTML = "FileReader is not supported...";
input.setAttribute('disabled', 'disabled');
} else {
input.addEventListener('change', readFile, false);
}
};
function readFile() {
var file = this.files[0];
if (!/image\/\w+/.test(file.type)) {
alert("image only please.");
return false;
}
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(e) {
var img = new Image,
width = 640, //image resize
quality = 0.8, //image quality
canvas = document.createElement("canvas"),
drawer = canvas.getContext("2d");
img.src = this.result;
img.onload = function() {
canvas.width = width;
canvas.height = width * (img.height / img.width);
drawer.drawImage(img, 0, 0, canvas.width, canvas.height);
img.src = canvas.toDataURL("image/jpeg", quality);
console.log(img.src);
result.innerHTML = '<img src="' + img.src + '" alt=""/>';
img_area.innerHTML = '<div class="sitetip">preview:</div><img src="' + img.src + '" alt=""/>';
}
}
}
html
<input type="file" value="image" id="img_input" />
<textarea id="result"></textarea>
<p id="img_area"></p>
后台压缩:
public static byte[] compressPicVersion2(MultipartFile myFile,int width, int height, boolean proportion ){
byte[] bytes = null;
try {
Image img = ImageIO.read(myFile.getInputStream());
if(img.getWidth(null) == -1) {
return null;
} else {
int newWidth;
int newHeight;
if (proportion == true) {
// double rate = (double)width/(double)img.getWidth(null);
// System.out.println("--------"+rate+"++"+img.getWidth(null));
// newWidth = (int) (img.getHeight(null)*rate);
// double wate = (double)height/(double)img.getHeight(null);
// newHeight = (int) (img.getHeight(null)*wate);
newWidth =(int) (img.getWidth(null)*0.5);
newHeight = (int) (img.getHeight(null)*0.5);
System.out.println("-----------"+newWidth);
} else {
newWidth = width;
newHeight = height;
}
BufferedImage tag = new BufferedImage((int)newWidth,(int)newHeight,BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(img,0,0,newWidth,newHeight,null);
ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write(tag, "jpg", out);
bytes = out.toByteArray();
}
} catch (IOException e) {
e.printStackTrace();
}
return bytes;
}
注意:导包import java.awt.Image;
import java.awt.image.BufferedImage;
- 注意在FF下,类似这样的处理方案必须确保canvas绘制和toDataUrl的处理是同步进行的,也就是不能是异步处理的,否则可能会出现其他事件触发页面组合(Composite)而导致canvas缓存被清空的情况,那样toDataUrl出来的会是空白字符串。
- 需要等image加载完成再做draw和转换的动作,否则一些浏览器会有问题。