原理 new一个image,然后 用canvas来绘图
代码语言:javascript复制function compress(base64, width, callback) {
var image = new Image();
image.src = base64;
image.onload = function () {
var height = (width / this.width) * this.height;
var canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, width, height);
ctx.drawImage(image, 0, 0, width, height);
var data = canvas.toDataURL('image/jpeg');
callback(data);
}
}
调用代码:
代码语言:javascript复制var file = e.target.files[0]
if (file) {
var reader = new FileReader();
reader.onload = function () {
compress(reader.result, 250, function (data) {
app.messages.push({
type: 'image',
self: true,
data: data
})
});
};
reader.readAsDataURL(file);
}实现效果图: