简体   繁体   English

将 Uint8Array 显示为图像

[英]Display an Uint8Array as image

Given a typed array such as:给定一个类型化数组,例如:

const myBuffer = new Uint8Array([255,0,0,255])

How could I obtain a base64 encoded an image , to be put in the DOM?我怎样才能获得一个 base64 编码的图像,并将其放入 DOM 中?

<img src={ whatToDoHere(myBuffer) }/>

I'd like to see a 1px x 1px red image.我想看一张 1px x 1px 的红色图像。

I'm reading a WebGL render target using gl.readPixels() .我正在使用gl.readPixels()读取 WebGL 渲染目标。 My mind melted from reading about a dozen different questions regarding this, and none of them solved my issue.阅读了十几个与此相关的不同问题后,我的思绪融化了,但没有一个解决了我的问题。

If I render directly to the canvas, I can use toDataURL on the DOM element (canvas) and get what I need.如果我直接渲染到画布,我可以在 DOM 元素(画布)上使用toDataURL并获得我需要的东西。 I'd like to do it from a target though, not the drawing buffer.不过,我想从目标而不是绘图缓冲区开始。

A solution would be to directly generate a data URL from webgl's canvas using canvas.toDataURL , which also supports image compression.一种解决方案是使用canvas.toDataURL从 webgl 的画布直接生成数据 URL,它也支持图像压缩。

This is a bit off topic.这有点题外话了。 Here a solution without WebGL or the Canvas.这是一个没有 WebGL 或 Canvas 的解决方案。 This is very simple using a Blob:使用 Blob 非常简单:

 // Small red dot image const content = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 5, 0, 0, 0, 5, 8, 6, 0, 0, 0, 141, 111, 38, 229, 0, 0, 0, 28, 73, 68, 65, 84, 8, 215, 99, 248, 255, 255, 63, 195, 127, 6, 32, 5, 195, 32, 18, 132, 208, 49, 241, 130, 88, 205, 4, 0, 14, 245, 53, 203, 209, 142, 14, 31, 0, 0, 0, 0, 73, 69, 78, 68, 174, 66, 96, 130]); document.getElementById('my-img').src = URL.createObjectURL( new Blob([content.buffer], { type: 'image/png' } /* (1) */) );
 Should display a small red dot: <img id="my-img">

(1) It also works without specifying the MIME type. (1) 它也可以在不指定 MIME 类型的情况下工作。

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

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