jspdf 到 addImage:错误提供的数据不是 JPEG

jspdf to addImage : error supplied data is not a JPEG

我正在尝试向我的 pdf 添加图像:

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

我得到这个错误:

Error: Supplied data is not a JPEG

但是,当我添加 base64 图像时:

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

它工作正常!

为什么第一个版本不起作用? 我正在尝试这个:

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

又是上面的错误!

这里发生了什么?解决方案是什么?

您可以使用 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;
}