3

I'm would like to load a jpeg image to a canvas from a binary array (currently trying with an Uint8Array). I've been looking all over the net for a solution but all I could find is converting the array to base64 and then loading the image which is not very efficient.

Here is my code used for loading the image:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<canvas id="MainImage" width="756" height="600">Your browser doesn't support html5</canvas>
<script type="text/javascript">
_Request = new XMLHttpRequest();
var url = "http://localhost/AAA/S.jpg";
try {
   _Request.onreadystatechange = function() {
      if (_Request.readyState == 4 && _Request.status == 200) {
         var downloadedBuffer = _Request.response;
         if (downloadedBuffer) {
            var binaryByteArr = new Uint8Array(downloadedBuffer);
         }
      }
      _Request.open('GET', url, true);
      _Request.responseType = 'arraybuffer';
      _Request.send();
} catch (e) {
}
</script>
</body>
</html>

I would like to load this processed array of the image to a canvas.

This is just a sample, my original code receives a binary array with multiple jpeg images in a single array so other methods wont work.

Any help would be appreciated

3
  • 1
    That's just the way it is. There is no other way than to convert the byte array to a base64 encoded data URL and use it as a src to an image, then draw the image to the canvas Commented Sep 24, 2013 at 8:23
  • This way is 'too wrong' to be 'just the way it is'. I'm sure there is another way. Commented Sep 24, 2013 at 13:44
  • I see no big difference between creating a data URL or an object URL. Either way you need to create an image and draw the image to the canvas. You cannot use the byte array "as is". createObjectURL is marked as "experimental technology" on MDN Commented Sep 24, 2013 at 13:48

1 Answer 1

4

Assuming you have a way of splitting the binary array into arrays per image (either by a known length or using the JPEG header to identify the new image) you can use Blob and an object URL:

Example (based on this example from MDN):

var imageData = GetTheTypedArraySomehow();
var blob = new Blob([imageData], {type: "image/jpeg"});
var url = URL.createObjectURL(blob);

Now you can set the url as src for an image::

var img = new Image();
img.onload = function() {
    /// draw image to canvas
    context.drawImage(this, x, y);
}
img.src = url;
Sign up to request clarification or add additional context in comments.

2 Comments

ReferenceError: GetTheTypedArraySomehow is not defined where did you define the function?
@guradio that is an imaginary function where you would get your own image data from.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.