Trying to compress img via canvas.toDataURL
I'm trying to work out img/canvas scaling but it's not working. I've got an image, and I want to compress it, so I'm using canvas to do this using the following code:
<img id='srcimg'>
<img id='copyimg'>
and
function doSendToCanvasThenCopyImg(srcimg, destimg) {
var scale = 1;
var natW = srcimg.naturalWidth;
var natH = srcimg.naturalHeight;
var newCanvas = document.createElement('canvas');
newCanvas.width = parseInt(natW * scale);
newCanvas.height = parseInt(natH * scale);
var ctx = newCanvas.getContext("2d");
ctx.drawImage(srcimg, 0, 0, natW, natH, 0, 0, newCanvas.width, newCanvas.height);
var base64 = newCanvas.toDataURL('image/jpeg', 1);
destimg.src = base64;
}
and
function scaleToFit(img, newW, natW, natH) {
var scale = newW / natW;
var newCanvas = document.createElement('canvas');
var ctx = newCanvas.getContext("2d");
ctx.drawImage(img, 0, 0, natW, natH, 0, 0, parseInt(natW * scale), parseInt(natH * scale));
var base64 = newCanvas.toDataURL('image/jpeg',1);
img.src = base64;
}
but this seems to only show the top left corner of the src image. Why is this and how can I get the whole image?
Secondly, I am trying to measure the diskspace size of the image, so I use the function:
function getImageSize(img) {
var can = document.createElement('canvas');
var natW = img.naturalWidth;
var natH = img.naturalHeight;
can.width = natW;
can.height = natH;
var ctx = can.getContext("2d");
ctx.drawImage(img, 0, 0, natW, natH, 0, 0, natW, natH);
var base64 = can.toDataURL('image/jpeg',1);
return base64.length;
}
But this seems to result in an incorrect result - after the copy the img [base64] src is blank - can anyone help?
I have a running sample found on https://jsfiddle.net/Abeeee/9bzk7h6w/ (sorry - it includes a very large base64 image as I couldn't find a way to include images in jsfiddle and external images will cause security issues with the script).
- When running the sample, and clicking [Run step 1] I see the resulting image as expected but with indicated image sizes wrongly stated.
- When running the sample, and clicking [Run step 1 and 2] I see only the partial result.
To recap - I'm trying to resize an image in javascript and want to see the resulting filesize as I go.
What goes on?
Thanks. Abe
from Recent Questions - Stack Overflow https://ift.tt/3tdBeiE
https://ift.tt/eA8V8J
Comments
Post a Comment