JS压缩图片并转换base64
// 调用
photoCompress(pic, 1080, 0, 0.3, function(base64Codes, path) {
Base64Url = base64Codes;
appendFile(pic);
});
/*
三个参数
file:一个是文件(类型是图片格式),
w:一个是文件压缩的后宽度,宽度越小,字节越小
objDiv:一个是容器或者回调函数
photoCompress()
*/
// 图片压缩的方法
// file:通过file控件上传的图片文件
// w: 图片宽度,0表示根据高度按比例
// h: 图片高度,0表示根据宽度按比例
// objDiv:回调函数
function photoCompress(file, w, h, qua, callback) {
var obj = {
width: w,
height: h,
quality: qua
}
if (w == 0) {
obj = {
height: h,
quality: qua
}
} else if (h == 0) {
obj = {
width: w,
quality: qua
}
}
canvasDataURL(file, obj, callback);
}
// path:需要压缩的Base64图片
function canvasDataURL(path, obj, callback) {
var img = new Image();
img.src = path;
img.crossOrigin = "anonymous"; //关键
img.onload = function() {
var that = this;
// 默认按比例压缩
var w = that.width,
h = that.height,
scale = w / h;
//alert(h)
w = obj.width || w;
h = obj.height || (w / scale);
//alert(h)
var quality = 0.7; // 默认图片质量为0.7
//生成canvas
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
// 创建属性节点
var anw = document.createAttribute("width");
anw.nodeValue = w;
var anh = document.createAttribute("height");
anh.nodeValue = h;
canvas.setAttributeNode(anw);
canvas.setAttributeNode(anh);
ctx.drawImage(that, 0, 0, w, h);
// 图像质量
if (obj.quality && obj.quality <= 1 && obj.quality > 0) {
quality = obj.quality;
}
var base64 = canvas.toDataURL('image/jpeg', quality);
// 回调函数返回base64的值
callback(base64, path);
}
}
/*** 根据图片生成画布*/
function convertImageToCanvas(image) {
var canvas = document.createElement("canvas");
canvas.width = image.width;
canvas.height = image.height;
canvas.getContext("2d").drawImage(image, 0, 0);
return canvas;
}