I hope someone here can help.
The function below correctly creates base64 strings from the images on my website.
If I manually add a larger b64 value (generated from from a 164k image) it works fine.
<img src="data:image/jpeg;base64,/9j/4AA..... etc
However, if I use this function on the same 164k image I only get “data:,” as the output value.
Is the canvas limited to the DataURL size it can output? If so what would be a better method to encode images programatically?
Thank you.
<script type="text/javascript">
function imageFetch(imgpath, imgname)
{
imageObj = new Image();
imageObj.src = imgpath + imgname;
var canvas = document.createElement('canvas');
canvas.width = imageObj.width;
canvas.height = imageObj.height;
var canvasContext = canvas.getContext('2d');
canvasContext.drawImage(imageObj, 0, 0, canvas.width, canvas.height);
var lenImgName = imgname.length;
var imgType = imgname.substring(lenImgName-3,lenImgName);
if (imgType == "jpg")
{
base64Data = canvas.toDataURL('image/jpeg');
}
if (imgType == "png")
{
base64Data = canvas.toDataURL('image/png');
}
return base64Data;
}
As pointed out by brodney you’ll get this result if the width or height of the canvas is 0 which it is because you do not wait for the image to load before you set the canvas size to the image’s width and height and those properties return 0 if the image is not fully loaded.