二进制数组到canvas [英] Binary array to canvas
问题描述
我想从一个二进制数组(目前尝试用Uint8Array)加载一个jpeg图像到画布。我一直在寻找所有的网络的解决方案,但我只能找到是将数组转换为base64,然后加载的图像,这是不是很有效率。
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.
这只是一个例子,我的原始代码接收一个二进制数组与多个jpeg图像在一个数组,所以其他方法不能工作。
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.
任何帮助将不胜感激。
推荐答案
假设你有一种方法将二进制数组分割成每个图像的数组长度或使用JPEG头标识新图像),您可以使用 Blob
和对象URL:
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:
示例(根据此示例来自MDN ):
var imageData = GetTheTypedArraySomehow();
var blob = new Blob([imageData], {type: "image/jpeg"});
var url = URL.createObjectURL(blob);
现在您可以将 url
code> src for a image ::
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;
这篇关于二进制数组到canvas的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!