Ryne Cheow Ryne Cheow - 1 year ago 121
Javascript Question

Converting data URI to image data

/**
* Converts data URI in 'image/png' format to an image data object
* @param dataURL Base64 encoded string
* @returns {ImageData/undefined}
*/
convertDataURLToImageData: function (dataURL) {
if (dataURL !== undefined && dataURL !== null) {
var canvas, context, image, imageData;
canvas = document.createElement('canvas');
canvas.width = 470;
canvas.height = 470;
context = canvas.getContext('2d');
image = new Image();

image.addEventListener('load', function(){
context.drawImage(image, 0, 0, canvas.width, canvas.height);
imageData = context.getImageData(0, 0, canvas.width, canvas.height);
//how do i return this?
}, false);
image.src = dataURL;

return imageData;
}
}


considering the snippet above, if I would like to get an array of image data from a data URL I wold draw it on a canvas , how do I return the image data?

Answer Source

The problem is that your function is asynchronous, because you are waiting for the load event.

Then, you could do something like

function convertDataURLToImageData(dataURL, callback) {
    if (dataURL !== undefined && dataURL !== null) {
        var canvas, context, image;
        canvas = document.createElement('canvas');
        canvas.width = 470;
        canvas.height = 470;
        context = canvas.getContext('2d');
        image = new Image();
        image.addEventListener('load', function(){
            context.drawImage(image, 0, 0, canvas.width, canvas.height);
            callback(context.getImageData(0, 0, canvas.width, canvas.height));
        }, false);
        image.src = dataURL;
    }
}

and call it like this:

convertDataURLToImageData(
    dataURL, function (imageData) {
         // Do something with imageData
    }
)