Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
266 views
in Technique[技术] by (71.8m points)

javascript - Binary array to canvas

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...