JavaScript - 从二进制JPG数据创建图像 [英] JavaScript - Creating an Image from binary JPG data

查看:261
本文介绍了JavaScript - 从二进制JPG数据创建图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于浏览器知道如何处理JPG文件,有没有办法动态地为它们提供JPG文件的实际二进制数据并允许它们对其进行解码?

Since browsers know how to handle JPG files, is there a way to give them the actual binary data of a JPG file dynamically and allowing them to decode it?

我无法将文件作为普通的image.src =path.jpg提供,因为数据最初是另一个在JS中解析的文件的一部分。

I can't supply the file as a normal image.src="path.jpg" because the data is originally a part of another file which is parsed in JS.

另外,我有奇怪的JPG文件存储alpha,所以像 https://github.com/notmasteryet/jpgjs这样的库无法处理它们。

In addition, I have weird JPG files that store alpha, and so libraries like https://github.com/notmasteryet/jpgjs can't handle them.

推荐答案

您可以使用 Blob 用于从二进制数据创建对象,您稍后将其作为图像解码的URL传递。假设您将二进制数据存储为类型数组,您可以执行以下操作:

You can use Blobs to create objects from binary data that you later pass as an url for image decoding. Assuming you have the binary data stored as typed array you could do something like this:

var blob = new Blob([myTypedArray], {type: 'application/octet-binary'});
var url = URL.createObjectURL(blob);

现在您可以将该网址作为图片来源传递:

Now you can pass that url as a source for image:

var img = new Image;
img.onload = function() {
    URL.revokeObjectURL(url);
    ...
};
img.src = url;

请注意,您仍然确保传入的数据是浏览器可以使用的有效图像格式处理。

Note that you still have make sure that the data you pass in is valid image format that the browser can handle.

这篇关于JavaScript - 从二进制JPG数据创建图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆