最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jspdf to addImage : error supplied data is not a JPEG - Stack Overflow

programmeradmin3浏览0评论

I am trying to add an image to my pdf:

var image = '../images/example.jpg';
doc.addImage(image, 'JPEG', 0, 0, 700, 145);

and I get this error:

Error: Supplied data is not a JPEG

however, when I add a base64 image:

var image = 'data:image/jpeg;base64,/9j/6GADS...'
doc.addImage(image, 'JPEG', 0, 0, 700, 145);

it works fine!

why is the first version not working? I am trying this:

var image = $base64.encode('../images/example.jpg')

the same error above again!

what is happening here? what is the solution?

I am trying to add an image to my pdf:

var image = '../images/example.jpg';
doc.addImage(image, 'JPEG', 0, 0, 700, 145);

and I get this error:

Error: Supplied data is not a JPEG

however, when I add a base64 image:

var image = 'data:image/jpeg;base64,/9j/6GADS...'
doc.addImage(image, 'JPEG', 0, 0, 700, 145);

it works fine!

why is the first version not working? I am trying this:

var image = $base64.encode('../images/example.jpg')

the same error above again!

what is happening here? what is the solution?

Share Improve this question asked Jun 11, 2017 at 18:54 BonnardBonnard 3892 gold badges9 silver badges27 bronze badges 1
  • I have this exact problem, but only on the live version, not on my local version. How is this possible, what is missing? I just updated the file, and now it's not working at all. Is there any other solution than below? I'm reading it similar to above but responsetype as blob – Fastersixth Commented Mar 17, 2020 at 12:09
Add a ment  | 

1 Answer 1

Reset to default 3

You can use this.

function toDataUrl(src, callback, outputFormat) {
  // Create an Image object
  var img = new Image();
  // Add CORS approval to prevent a tainted canvas
  img.crossOrigin = 'Anonymous';
  img.onload = function() {
    // Create an html canvas element
    var canvas = document.createElement('CANVAS');
    // Create a 2d context
    var ctx = canvas.getContext('2d');
    var dataURL;
    // Resize the canavas to the image dimensions
    canvas.height = this.height;
    canvas.width = this.width;
    // Draw the image to a canvas
    ctx.drawImage(this, 0, 0);
    // Convert the canvas to a data url
    dataURL = canvas.toDataURL(outputFormat);
    // Return the data url via callback
    callback(dataURL);
    // Mark the canvas to be ready for garbage 
    // collection
    canvas = null;
  };
  // Load the image
  img.src = src;
}
发布评论

评论列表(0)

  1. 暂无评论