如何解决如何将 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 spec,CanvasImageSource
是
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 举报,一经查实,本站将立刻删除。