简体   繁体   English

在 JavaScript 中将编码的 JPEG 图像转换为 Uint8Array

[英]Converting an encoded JPEG image to Uint8Array in JavaScript

I have a python server that sends a frame of RGB data to my JS script via a websocket.我有一个 python 服务器,它通过 websocket 将一帧 RGB 数据发送到我的 JS 脚本。 The frame is encoded using simplejpeg python package.该帧使用 simplejpeg python package 编码。 The code looks like this:代码如下所示:

jpeg_frame = simplejpeg.encode_jpeg(image=color_frame, quality=85,colorspace='RGB', colorsubsampling='444', fastdct=True)

jpeg_frame is passed to the websocket and sent to the JS script. jpeg_frame 传递给 websocket 并发送到 JS 脚本。

On the JS side however, I would like to decompress the image and have it in the form of a Uint8Array so that I can work with the data.然而,在 JS 方面,我想解压缩图像并将其以 Uint8Array 的形式保存,以便我可以处理数据。 The image does not have to be viewed.不必查看图像。

The data recieved is in the form of ArrayBuffer.接收到的数据是 ArrayBuffer 的形式。

This is what I have so far.这就是我到目前为止所拥有的。

socketio.on('colorFrame',(data)=>{
    var mime = 'image/jpeg';
    var a = new Uint8Array(data);
    var nb = a.length;
    if (nb < 4)
        return null;
    var binary = "";
    for (var i = 0; i < nb; i++)
        binary += String.fromCharCode(a[i]);
    var base64 = window.btoa(binary);
    var image = new Image();
    image.src = 'data:' + mime + ';base64,' + base64;
    
    var canvas = document.createElement('canvas');
    var ctx = canvas.getContext('2d');

    ctx.drawImage(image,0,0)

    image.onload = function(){
        var image_data = ctx.getImageData(0,0, 960, 540);
        console.log(image_data);
    };
});

So far I could not yet figure out how I can decompress the image.到目前为止,我还不知道如何解压缩图像。 I dont mind the inaccuracy of the lossy compression, I just want the image back to its original resolution and be able to convert it to a Uint8Array.我不介意有损压缩的不准确性,我只希望图像恢复到其原始分辨率并能够将其转换为 Uint8Array。

What is the simplest way to get JPEG decoding working in a JS scrip?让 JPEG 解码在 JS 脚本中工作的最简单方法是什么?

There is an excellent article "Decoding a PNG Image in JavaScript" that answers the literal question.有一篇优秀的文章“Decoding a PNG Image in JavaScript”回答了字面问题。 It's a non-trivial answer.这是一个不平凡的答案。 (Note: I am not the author of the article) (注:我不是文章作者)

However然而

Based on your code, it looks like you might not care about actually decoding the Image yourself.根据您的代码,您可能并不关心自己实际解码图像。 If you just want to display it, take a look at this StackOverflow question如果您只想显示它,请查看此 StackOverflow 问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM