简体   繁体   中英

How to use canvas.toDataURL() to get base64 of image in Adobe AIR?

Is it possible to use canvas.toDataURL() in Adobe AIR?

When I try I get the following error:

Error: SECURITY_ERR: DOM Exception 18

Adobe AIR enforces same origin for images used in the canvas API. Once you've used something from another domain in your canvas, you can't get pixel data back out of it. However, you can make use of the Loader class to get the pixel data, and convert it into a canvas ImageData.

For example:

function getDataURL(url, callback) {
  var loader = new air.Loader();
  loader.contentLoaderInfo.addEventListener(air.Event.COMPLETE, function(event) {
    var bitmapData = loader.content.bitmapData;

    var canvas = document.createElement('canvas');
    canvas.width = bitmapData.width;
    canvas.height = bitmapData.height;
    var context = canvas.getContext('2d');
    var imageData = context.createImageData(canvas.width, canvas.height);

    var dst = imageData.data;
    var src = bitmapData.getPixels(bitmapData.rect);
    src.position = 0;

    var i = 0;
    while (i < dst.length) {
      var alpha = src.readUnsignedByte();
      dst[i++] = src.readUnsignedByte();
      dst[i++] = src.readUnsignedByte();
      dst[i++] = src.readUnsignedByte();
      dst[i++] = alpha;
    }

    context.putImageData(imageData, 0, 0);
    callback(canvas.toDataURL());
  });
  loader.load(new air.URLRequest(url));
}

window.addEventListener('load', function() {
  getDataURL('http://www.google.com/images/logo.gif', function(dataURL) {
    air.trace(dataURL);
  });
}, false);

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