4

I want to use the (pica library) for image resize, but it asks me for a Uint8Array and i only have an Image object with the

src = 'data:image/jpeg;base64,/9j/4AAQ...'

I have no idea how to turn this into a Uint8Array, any thoughts?
Thanks

1
  • 2
    From memory, the data stored in a canvas is stored in a typed array of the same type. So, you could draw the image to a canvas, then call getImageData on the canvas. Inside the returned object, you'll have an array like you wish. Of course, if you're going to go via a canvas anyway you can just do the resize yourself, no need for the library. Here's an example of scaling an image with a canvas here: stackoverflow.com/questions/28773631/… (just ignore the uploading part) Commented Mar 1, 2015 at 17:55

1 Answer 1

3

You will need to apply the image to a canvas and use getImageData().

Here's a simple example of how it can be done:

//create canvas, set base64 test img
var canvas = document.createElement('canvas'),
    ctx = canvas.getContext('2d'),
    base64 = 'data:image/jpeg;base64...'; //base64 string

//size canvas
canvas.width = 34,
canvas.height = 34;

//create image, set src to base64 and onload draw to canvas
var image = new Image();
image.onload = (function(canvas, ctx){
    return function(){
        ctx.drawImage(this, 0, 0);

        //now we can finally get a Uint8ClampedArray
        var imageData = ctx.getImageData(0, 0, 34, 34);
        console.log(imageData.data);
    };
})(canvas, ctx);
image.src = base64;

jsfiddle

Sign up to request clarification or add additional context in comments.

2 Comments

Hi @EvilZebra! Is that possible to get same result from ctx.getImageData without using Image class ?
I am afraid not @SergeyVolkov, the only other method available for putting image data into the canvas would be putImageData() which itself requires a Uint8ClampedArray. And we can not easily extract the pixel color data from a base64 encoded image as the string contains image headers and other data.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.