-1

我在我的 chrome 应用程序上工作,内容安全政策令人不安。我想从 json (string/object/array 我不知道)中获取 jpeg 图像,但是 csp 每次都阻止我。现在我知道使用数据链接更容易,所以我搜索了一个转换器

function getdt(img) {
    // Create an empty canvas element
    var canvas = document.createElement("canvas");

    // Copy the image contents to the canvas
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0, img.width, img.height);

    // Get the data-URL formatted image.
    var dataURL = canvas.toDataURL("image/png");

    return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}

//Example
getdt('http://ms01.oe3.fm/oe3metafiles/Pictures/200/929203.22.jpg');

不幸的是,这不起作用。错误消息是这样的:

Uncaught TypeError: 
Failed to execute 'drawImage' on 'CanvasRenderingContext2D': 
No function was found that matched the signature provided.

我希望有人可以帮助我:) 对不起我的英语不好

4

1 回答 1

1

You have 3 problems with your code:

  1. As @A.Wolff infers, your img is invalid. Canvas requires a full Image object to draw, not just a URL. So you will have to "new up" an image object var img=new Image();

  2. The image is loaded asynchronously so you must use put your drawImage and toDataURL inside the img.onload callback. This allows the image to be fully loaded before you try to use it. This also means instead of return dataURL you must also put all the code that uses the dataURL inside the onload callback. (Yes, I know, that's messy, but you must do it that way or else the image isn't fully loaded)

  3. For good security reasons, to use toDataURL your image must be hosted on the same domain as your webpage. If they are different domains, toDataURL will fail with a Security Error. This security issue is an involved topic so here is where you can learn what's necessary to avoid the Security Error: http://enable-cors.org/

...And: toDataURL's jpg encoding uses image/jpeg so you need to change your regEx.

Here's your code refactored and using an image that is hosted in a way to not create the Security Error:

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;


var img=new Image();
img.crossOrigin='anonymous';
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/multple/sun.png";
function start(){

  canvas.width=img.width;
  canvas.height=img.height;
  ctx.drawImage(img,0,0);
  var dataURL=canvas.toDataURL(); // png is the default format

  dataURL=dataURL.replace(/^data:image\/(png|jpeg);base64,/, "");

  // Your dataURL is now available
  // Use it as desired
  alert('The dataURL is '+dataURL.length+' characters long ans starts with: '+dataURL.substring(0,20));

}
body{ background-color: ivory; padding:10px; }
#canvas{border:1px solid red;}
<canvas id="canvas" width=300 height=300></canvas>

于 2015-02-14T16:16:43.277 回答