如何将 Uint8Array 转换为 CanvasImageSource? 1.返回 this.gl.canvas2.使用 JSDOM3.使用 JSDOM 创建一个 HTMLImageElement 并将 src 设置为 base64 URL

如何解决如何将 Uint8Array 转换为 CanvasImageSource? 1.返回 this.gl.canvas2.使用 JSDOM3.使用 JSDOM 创建一个 HTMLImageElement 并将 src 设置为 base64 URL

在 TypeScript (NodeJS) 中,我正在努力将带有位图图像数据的 Uint8Array 转换为 CanvasImageSource 类型。

更多背景

我正在开发一个将在浏览器和 NodeJS 环境中使用的打字稿库。该库使用 WebGL 进行图像操作,因此在 NodeJS 环境中,我尝试利用 headless-gl。我的库包含一个函数 (getCanvasImageSource),它返回一个 CanvasImageSource 供客户端使用。

为了提出问题,删除了一堆代码。 WebGL 着色器将在 gl 上下文中创建所需的图像,客户端可以通过 CanvasImageSource 检索该图像。这在浏览器客户端中按预期工作。

/**
 * Browser version of the library.
 */
export class MyLibrary {
    protected gl!: WebGLRenderingContext;
    protected width: number;
    protected height: number;

    public getCanvasImageSource(): CanvasImageSource {
        return this.gl.canvas;
    }

    /**
     * the GL context can only be created in a browser.
     */
    protected makeGL(): WebGLRenderingContext {
        const canvas = document.createElement('canvas');
        canvas.width = this.width;
        canvas.height = this.height;
        const glContext = canvas.getContext('webgl');
        if (!glContext) {
            throw new Error("Unable to initialize WebGL. This browser or device may not support it.");
        }
        return glContext;
    }
}
import gl from 'gl';

/**
 * A subclass of MyLibrary that overrides the browser-specific functionality.
 */
export class MyHeadlessLibrary extends MyLibrary {
    public getCanvasImageSource(): CanvasImageSource {
        // The canvas is `undefined` from headless-gl.
        // this.gl.canvas === undefined;

        // But,I can read the pixel data as a bitmap.
        const format = this.gl.RGBA;
        const type = this.gl.UNSIGNED_BYTE;
        const bitmapData = new Uint8Array(this.width * this.height * 4);
        this.gl.readPixels(0,this.width,this.height,format,type,bitmapData);

        // This is where I am struggling...
        // Is there a way to convert my `bitmapData` into a `CanvasImageSource`?
    }

    /**
     * Overrides the browser's WebGL context with the headless-gl implementation.
     */
    protected makeGL(): WebGLRenderingContext {
        const glContext = gl(this.width,this.height);
        return glContext;
    }
}

但是,我正在努力寻找一种方法来成功将从 headless-gl 上下文读取的 Uint8Array 数据转换为 CanvasImageSource 对象。

以下是我尝试过的一些方法:

1.返回 this.gl.canvas

在 headless-gl 的情况下,这最终是 undefined

2.使用 JSDOM

JSDOM 的画布不支持 WebGL 渲染上下文。

3.使用 JSDOM 创建一个 HTMLImageElement 并将 src 设置为 base64 URL

我还不太明白为什么,但这里的承诺从来没有解决或拒绝。这导致我的库超时。所以也许这个策略会奏效,但我的实施存在问题。

此策略已用于库的其他领域,但没有涉及 headless-gl 甚至 WebGL。只是 2D 画布上下文。

import gl from 'gl';
import { JSDOM } from 'jsdom';

export class MyHeadlessLibrary extends MyLibrary {
    /**
     * In this attempt,I changed the return type to Promise<CanvasImageSource> here,in MyLibrary,and in the client code.
     */
    public getCanvasImageSource(): Promise<CanvasImageSource> {
        // The canvas is `undefined` from headless-gl.
        // this.gl.canvas === undefined;

        // But,bitmapData);

        // Create a DOM and HTMLImageElement.
        const html: string = `<!DOCTYPE html><html><head><meta charset="utf-8" /><title>DOM</title></head><body></body></html>`;
        const dom = new JSDOM(html);
        const img = dom.window.document.createElement('img');

        // Create a base64 data URL
        const buffer = Buffer.from(bitmapData);
        const dataurl = `data:image/bmp;base64,${buffer.toString('base64')}`;

        // Set the image source and wrap the result in a promise
        return new Promise((resolve,reject) => {
            img.onerror = reject;
            img.onload = () => resolve(img);
            img.src = dataurl;
        });
    }
}

如果我的代码中出现问题,请告诉我,或者指出此问题的潜在解决方案!

解决方法

根据the specCanvasImageSource

typedef (HTMLOrSVGImageElement or
         HTMLVideoElement or
         HTMLCanvasElement or
         ImageBitmap or
         OffscreenCanvas) CanvasImageSource;

所以这取决于您的需求。如果您不需要任何 alpha,那么其中之一是 HTMLCanvasElement,因此您可以使用给定的像素

function pixelsToCanvas(pixels,width,height) {
  const canvas = document.createElement('canvas');
  canvas.width = width;
  canvas.height = height;
  const ctx = canvas.getContext('2d');
  const imgData = ctx.createImageData(width,height);
  imgData.data.set(pixels);
  ctx.putImageData(imgData,0);

  // flip the image
  ctx.scale(1,-1);
  ctx.globalCompositeOperation = 'copy';
  ctx.drawImage(canvas,-height,height);

  return canvas;
}

只要您没有 alpha 或者您不关心有损 alpha,这应该有效。注意:该代码假定您提供unpremliplied alpha

问题是像素可能具有像 255,192,128,0 这样的像素。但是因为 alpha 为零,所以当你通过上面的函数传递它时,你会在画布中得到 0,0,因为画布总是使用预乘的 alpha。这可能不是问题,因为对于大多数用例,255,0 无论如何都会显示为 0,0,但如果您有特殊用例,则此解决方案将不起作用。

注意:您需要 the canvas package


至于 dataURL 示例中的图像,此代码毫无意义

// Create a base64 data URL
const buffer = Buffer.from(bitmapData);
const dataurl = `data:image/bmp;base64,${buffer.toString('base64')}`;

首先,是否支持 image/bmp 取决于浏览器,因此 JSDOM 可能不支持 image/bmp,但代码未提供进一步的 a bmp file has a header。没有该标头,任何 API 都无法知道数据中的内容。如果你给它 256 字节,那么每像素图像是 8x8 4 字节吗?每像素 16x4 4byte 的图像?黑白 32x64 1 位/像素图像?等等。你需要标题。

也许编写标题会使代码起作用?

function convertPixelsToBMP(pixels,height) {
  const BYTES_PER_PIXEL = 4;
  const FILE_HEADER_SIZE = 14;
  const INFO_HEADER_SIZE = 40;

  const dst = new Uint8Array(FILE_HEADER_SIZE + INFO_HEADER_SIZE + width * height * 4);
  
  {
    const data = new DataView(dst.buffer);
    const fileSize = FILE_HEADER_SIZE + INFO_HEADER_SIZE + (width * height * 4);

    data.setUint8 ( 0,0x42); // 'B'
    data.setUint8 ( 1,0x4D); // 'M'
    data.setUint32( 2,fileSize,true)
    data.setUint8 (10,FILE_HEADER_SIZE + INFO_HEADER_SIZE);

    data.setUint32(14,INFO_HEADER_SIZE,true);
    data.setUint32(18,true);
    data.setUint32(22,height,true);
    data.setUint16(26,1,true);
    data.setUint16(28,BYTES_PER_PIXEL * 8,true);
  }

  // bmp expects colors in BGRA format
  const pdst = new Uint8Array(dst.buffer,FILE_HEADER_SIZE + INFO_HEADER_SIZE);
  for (let i = 0; i < pixels.length; i += 4) {
    pdst[i    ] = pixels[i + 2];
    pdst[i + 1] = pixels[i + 1];
    pdst[i + 2] = pixels[i + 0];
    pdst[i + 3] = pixels[i + 3];
  }
  return dst;
}

注意:此代码还假定您提供预乘 alpha。

,

@gman,谢谢你的帮助!这是有道理的,我需要 base64 URL 的标头,但无论如何我都不需要。返回 HTMLCanvasElement 足以满足我的需要。图像中有一些 alpha,但预乘 alpha 不是问题。

我遇到的另一件事是生成的图像被垂直翻转。我认为这是因为 WebGL 和 2D 画布坐标系的差异。我通过 looping through the pixels & swapping rows 解决了这个问题。

最终的解决方案如下所示:

export class MyHeadlessLibrary extends MyLibrary {
    public getCanvasImageSource(): CanvasImageSource {
        // read the pixel data
        const pixels = new Uint8Array(this.width * this.height * 4);
        this.gl.readPixels(0,this.width,this.height,this.gl.RGBA,this.gl.UNSIGNED_BYTE,pixels);

        // create a headless canvas & 2d context
        const html: string = `<!DOCTYPE html><html><head><meta charset="utf-8" /><title>DOM</title></head><body></body></html>`;
        const dom = new JSDOM(html);
        const canvas = dom.window.document.createElement('canvas');
        canvas.width = this.width;
        canvas.height = this.height;
        const ctx = canvas.getContext('2d');
        if (!ctx) {
            throw Error("Unable to create a 2D render context");
        }

        // flip the image
        const bytesPerRow = this.width * 4;
        const temp = new Uint8Array(bytesPerRow);
        for (let y = 0; y < this.height / 2; y += 1) {
            const topOffset = y * bytesPerRow;
            const bottomOffset = (this.height - y - 1) * bytesPerRow;
            temp.set(pixels.subarray(topOffset,topOffset + bytesPerRow));
            pixels.copyWithin(topOffset,bottomOffset,bottomOffset + bytesPerRow);
            pixels.set(temp,bottomOffset);
        }

        // Draw the pixels into the new canvas
        const imgData = ctx.createImageData(this.width,this.height);
        imgData.data.set(pixels);
        ctx.putImageData(imgData,0);

        return canvas;
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res