functioncutImageBase64(imgSrc,wid,quality) {//压缩上上传图片var img = new Image();
img.src = imgSrc;
img.onload = function() {var that = this;
//生成比例var w = that.width,
h = that.height,
scale = w / h;
w = wid || w;
h = w / scale;
//生成canvasvar canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
$(canvas).attr({ width: w, height: h });
ctx.drawImage(that, 0, 0, w, h);
// 生成base64
base64 = canvas.toDataURL('image/jpeg', quality || 0.6);
// $('#pic').attr('src',base64); // 显示压缩后的图片
};
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
动态更改form表单提交
var formData = new FormData(document.getElementById('registerForm'));
formData.append("name", '12222');
formData.append("file", convertBase64UrlToBlob(fileImg)); // fileImg是图片的base64字符串
1
2
3
1
2
3
base64图片转file文件提交
将剪切后的base64图片转成file文件提交,
/**
* 将以base64的图片url数据转换为Blob
* @param urlData
* 用url方式表示的base64图片数据
*/
function convertBase64UrlToBlob(urlData){
var bytes=window.atob(urlData.split(',')[1]); //去掉url的头,并转换为byte//处理异常,将ascii码小于0的转换为大于0var ab = new ArrayBuffer(bytes.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < bytes.length; i++) {
ia[i] = bytes.charCodeAt(i);
}
returnnew Blob( [ab] , {type : 'image/png'});
}