java读取图片画布大小_使用Java来调整图像的大小而无需在DOM上渲染画布

However when i create an off screen canvas using

const canvas = document.createElement('canvas');

the result image is transparent and the size does not even match the parameters.

If i draw on a canvas from the DOM everything works fine

const canvas = document.getElementById('canvas');

Here is my resize function that keeps the input image ratio :

resizeImage(file) {

const canvas = document.createElement('canvas');

// const canvas = document.getElementById('canvas');

const context = (canvas).getContext('2d');

// set maximum width and height of output image

const maxW = 400;

const maxH = 400;

const img = new Image;

img.onload = function () {

const iw = img.width;

const ih = img.height;

const scale = Math.min((maxW / iw), (maxH / ih));

const iwScaled = iw * scale;

const ihScaled = ih * scale;

console.log(iwScaled + ' ' + ihScaled);

(canvas).width = iwScaled;

(canvas).height = ihScaled;

context.drawImage(img, 0, 0, iwScaled, ihScaled);

}

img.src = URL.createObjectURL(file);

// retrieve output img in base64 format

console.log((canvas).toDataURL());

}

It takes a file (File) from a HTML input as parameter.

Any help would be appreciated, thank you.

解决方案

you get a Base-64 image when load is complete.

function resizeImage(file) {

var canvas = document.createElement('canvas');

var context = canvas.getContext('2d');

var maxW = 400;

var maxH = 400;

var img = document.createElement('img');

img.onload = function() {

var iw = img.width;

var ih = img.height;

var scale = Math.min((maxW / iw), (maxH / ih));

var iwScaled = iw * scale;

var ihScaled = ih * scale;

canvas.width = iwScaled;

canvas.height = ihScaled;

context.drawImage(img, 0, 0, iwScaled, ihScaled);

console.log(canvas.toDataURL());

document.body.innerHTML+=canvas.toDataURL();

}

img.src = URL.createObjectURL(file);

}

document.getElementById("file").addEventListener("change", function() {

file = file.files[0];

if (file) {

resizeImage(file);

}

});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值