将帧缓冲区转储转换为图像(bmp、png 等)

时间:2021-03-17 12:11:09

标签: javascript html linux framebuffer

我有一个服务器,我在其中使用 cat /dev/fb0 > fbdump.raw 转储帧缓冲区数据并将此文件的内容发送到 Web 客户端以显示为屏幕截图。在发布问题之前尝试了很多链接,但没有一个有助于在 HTML/JS 客户端呈现图像。

客户端是否需要任何处理,或者在 JavaScript 中是否有任何现成的 API 可用?任何建议表示赞赏。提前致谢。

引用链接:

1 个答案:

答案 0 :(得分:1)

您可以将 ImageData(存储在 Uint8ClampedArray 中的原始 RGBA 图像数据)放在画布上。

您必须通过交换红色和蓝色将帧缓冲区转储 (BGRA) 转换为 RGBA。 将 alpha 设置为 255(不透明)也是必要的,因为 linux 帧缓冲区不使用 alpha 通道,因此它通常为 0(透明)。

fetch("fbdump.raw") // load the dump
.then(response => response.arrayBuffer()) // convert the response to a ArraBuffer
.then(array_buffer => {
    let canvas = document.querySelector("canvas") // get the canvas
    let ctx = canvas.getContext("2d") // get the context
    let raw_data = new Uint8ClampedArray(array_buffer) // use the ArrayBuffer as a Uint8ClampedArray for easier acces and the constructor of ImageData needs a Uint8ClampedArray
    for (let i = 0; i < raw_data.length; i += 4) {
        // convert the BGRA dump to RGBA
        let b = raw_data[i + 0]
        raw_data[i + 0] = raw_data[i + 2]
        raw_data[i + 2] = b
        raw_data[i + 3] = 255 // set alpha to 255 to make it non transparent (the alpha ist set to 0 and is unused in the linux framebuffer)
    }

    let image_data = new ImageData(raw_data, 1920, 1080) // create a new ImageData object with a resolution of 1920x1080

    // set the canvas resolution to 1920x1080
    canvas.width = 1920
    canvas.height = 1080

    ctx.putImageData(image_data, 0, 0) // puts the image on the canvas, starting at (0,0)
})

此代码假定帧缓冲区的分辨率为 1920x1080 且采用 BGRA 像素格式。