3

I am retrieving a byte array of a pictureStream from a .net webservice. the JSON byte array response looks like this:

[137, 80, 78, 372, 617 more...]

I am trying to convert this byte array and draw it into an HTML canvas like this

var context = document.getElementById('boxcover').getContext('2d');
context.putImageData(movies.PictureStream, 0, 0);

But this doesn't work. I have no access the modify the webservice, so I am looking to convert this byte array into a picture using Javascript only. Also, I can't use server side scripting, client side only.

Thanks for the help

Here is an example of how the byte array comes in : http://www.copypastecode.com/33072/

shitburg
  • 190
  • 1
  • 9

2 Answers2

2

It depends what exactly is in the byte array. If it's a series of RGB or RGBA values, you can use getImageData/putImageData to draw it such as Kieranmaine mentioned.

But if the byte array is simply the data from a jpeg or other image format, you likely won't be able to access the individual pixel data in that manner. In such a case you might try converting it to base 64 to create a dataURI, creating an image element, setting the source to that dataURI and using drawImage to place it on the canvas.

To convert from a byte array to a data URI, you'll need to know the mime type first. But if you know it, try this code.

'data:image/png;base64,' + btoa(String.fromCharCode.apply(this, byteArray));

After setting the src attribute of the img element it's possible you may need to wait for its load event to fire before calling the context's drawImage() method.

Kyle Jones
  • 536
  • 3
  • 5
  • I believe the data is coming from PNG's or JPEG's, using the ReadBytes method in .net can you give me an example of converting the raw byte stream into base64? – shitburg Jul 22 '10 at 23:03
  • window.btoa will convert an ASCII string to base 64; I've went back and included an example in my answer. – Kyle Jones Jul 23 '10 at 05:04
0

You need to retrieve the canvas image data using the method getImageData(x, y, width, height) and then modify each pixel with values from your byte array.

I've created a small demo that draws red, green and blue 3 pixel long lines by calling getImageData and then update the image data using a byte array. Here's the url:

http://jsfiddle.net/WXfPF/1/

Also see this answer for additional information getPixel from HTML Canvas?.

Community
  • 1
  • 1
Castrohenge
  • 8,525
  • 5
  • 39
  • 66
  • 1
    Pretty sure `imageData.data = byteArray` will work just as well assigning every single index in a loop. http://jsfiddle.net/WXfPF/2/ – MooGoo Jul 23 '10 at 01:32
  • Thanks for that . Seems to work in FF but not chrome, although it doesn't throw an exception. – Castrohenge Jul 23 '10 at 08:03