JavaScript 压缩图片
原理 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);
}
}
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);
}
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);
}