clamp
clamp

Reputation: 34026

Javascript: loading image from bytearray

In Javascript you have the ByteArray type and some views on it as described here: https://developer.mozilla.org/en-US/docs/JavaScript/Typed_arrays

is it possible to store image data in such bytes and if yes, how can i display such an image? png or jpg?

Upvotes: 0

Views: 2206

Answers (1)

wendelbsilva
wendelbsilva

Reputation: 772

Yes, you can store an image using the typed arrays.

Im not sure what you want actually. If you want to create an HTMLImageElement from a ByteArray, you can do something similar as cited in here and here.

If you want to get the bytes from an Image, that would be trickier. You can draw the ImageElement to HTML canvas, and them get the URI back using toDataURL.

I just tried to get the data using canvas and it worked.

var myCanvas = document.getElementById('my_canvas_id');
var ctx = myCanvas.getContext('2d');
var img = new Image;
img.onload = function(){
    myCanvas.width = img.width;
    myCanvas.height = img.height;
    ctx.drawImage(img,0,0); // Or at whatever offset you like
    alert(myCanvas.toDataURL());
};
img.src = "logo4w.png";

Although, the method toDataURL() do not allow you to perform this operation if the image you draw on canvas comes from outside the website domain.

Upvotes: 1

Related Questions