简体   繁体   中英

Unable to load an Image into Canvas and get base64 encoding for that image

I am trying to generate a PDF from HTML using jspdf plugin. I am stuck with loading Images into PDF. There is a function addImage() in plugin which takes base64 encoding of an image, but converting an image to base64 is not working.

I have used below two ways

//Create canvas, draw image in context and get the data url

imgToDataURL =  function (img, outputFormat){
        var canvas = document.createElement('canvas');
        canvas.width = 20;
        canvas.height = 20;
        var c = canvas.getContext('2d');
        c.height = img.height;
        c.width=img.width;
        c.drawImage(img, 0, 0);
        c.save();
        var dataurl = canvas.toDataURL(outputFormat);
        return dataurl;

    }

var img = new Image();
img.crossOrigin = 'Anonymous';
img.src = "image path"
img.height= 60;
img.width=60;
var dataURL = this.imgToDataURL(img,"image/jpeg");
renderer.pdf.addImage(dataURL, 'png',x+padding,y + this.internal.getLineHeight(),imageWidth,imageHeight);

This is printing wrong dataURL I am getting a white image. If I hard code the base64 code ie return a hardcoded dataURL then addImage works fine. So the issue is with canvas.toDataURL which is giving me wrong output

this is the 2nd way

convertImgToBase64URL =  function (url, callback, outputFormat){
    var img = new Image();
    img.crossOrigin = 'Anonymous';
    img.onload = function(){
        var canvas = document.createElement('CANVAS'),
        ctx = canvas.getContext('2d'), dataURL;
        canvas.height = this.height;
        canvas.width = this.width;
        ctx.drawImage(this, 0, 0);
        dataURL = canvas.toDataURL(outputFormat);
        callback(dataURL);
        canvas = null; 
    };
    img.src = url;
}

this.convertImgToBase64URL("Image Path",function(base64){

    renderer.pdf.addImage(base64, 'PNG', 20, 20,48,48);
})

I have run this inside a javascript and the onload function is not even running I am not sure what is my mistake is.

Please suggest me what mistake I am doing in either way

In the first you missed assigning an onload function to your image. For that reason, the moment you try to create the dataURL, the image might not be loaded yet, ergo, the blank image. You could try changing the last few lines to this:

...
img.width=60;
img.onload = function () {
  var dataURL = this.imgToDataURL(img,"image/jpeg");
  renderer.pdf.addImage(dataURL, 'png',x+padding,y + this.internal.getLineHeight(),imageWidth,imageHeight);
}
img.src = "image path";

As for the second one, there seems to be a problem with the convertImgToBase64URL() which accepts 3 parameters, but you are passing 2. In you example, outputFormat parameter is undefined .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM