如何将 Uint8Array 转换为 CanvasImageSource?
How to convert a Uint8Array to a CanvasImageSource?
在 TypeScript (NodeJS) 中,我正在努力将带有位图图像数据的 Uint8Array 转换为 CanvasImageSource 类型。
更多上下文
我正在开发一个将在浏览器和 NodeJS 环境中使用的打字稿库。该库使用 WebGL 进行图像操作,因此在 NodeJS 环境中,我试图利用 headless-gl. My library includes a function (getCanvasImageSource
) that returns a 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, 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。 Returnthis.gl.canvas
在 headless-gl 的情况下,这最终是 undefined
。
2。使用 JSDOM
JSDOM 的 canvas 不支持 WebGL 渲染上下文。
3。使用 JSDOM 创建一个 HTMLImageElement 并将 src 设置为 base64 URL
我还不太明白为什么,但这里的承诺永远不会解决或拒绝。这导致我的库超时。所以也许这个策略会奏效,但我的实施存在问题。
此策略已用于库的其他领域,但 none 涉及 headless-gl 甚至 WebGL。只是二维 canvas 上下文。
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, 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, 0, this.width, this.height, format, type, 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, 0);
// flip the image
ctx.scale(1, -1);
ctx.globalCompositeOperation = 'copy';
ctx.drawImage(canvas, 0, -height, width, height);
return canvas;
}
只要您没有 alpha 或者您不关心有损 alpha,这应该可以工作。注意:代码假定您提供 unpremliplied alpha
问题是像素可能有这样的像素 255, 192, 128, 0
。但是因为 alpha 是零,当你通过上面的函数传递它时,你会在 canvas 中得到 0, 0, 0, 0
因为 canvases 总是使用预乘的 alpha。这可能不是问题,因为对于大多数用例,255, 192, 128, 0
无论如何都显示为 0,0,0,0
,但如果您有特殊用例,那么此解决方案将不起作用。
注意:您需要 the canvas package
至于您的 Image from 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 代码未提供。没有那个 header 任何 API 都无法知道数据中的内容。如果你给它 256 字节是每像素图像 8x8 4 字节吗?每像素 16x4 4 字节的图像?黑白 32x64 每像素 1 位图像?等..你需要 header.
也许编写 header 会使该代码起作用?
function convertPixelsToBMP(pixels, width, 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, width, 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;
}
注意:此代码还假设您提供 un 预乘 alpha。
@gman,谢谢你的帮助!这是有道理的,我需要 base64 URL 的 header,但我并不需要它。返回 HTMLCanvasElement
足以满足我的需要。图像中有一些 alpha,但预乘 alpha 不是问题。
我 运行 感兴趣的另一件事是生成的图像被垂直翻转。我认为这是因为 WebGL 和 2D canvas 坐标系的差异。我通过 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, 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, 0);
return canvas;
}
}
在 TypeScript (NodeJS) 中,我正在努力将带有位图图像数据的 Uint8Array 转换为 CanvasImageSource 类型。
更多上下文
我正在开发一个将在浏览器和 NodeJS 环境中使用的打字稿库。该库使用 WebGL 进行图像操作,因此在 NodeJS 环境中,我试图利用 headless-gl. My library includes a function (getCanvasImageSource
) that returns a 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, 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。 Returnthis.gl.canvas
在 headless-gl 的情况下,这最终是 undefined
。
2。使用 JSDOM
JSDOM 的 canvas 不支持 WebGL 渲染上下文。
3。使用 JSDOM 创建一个 HTMLImageElement 并将 src 设置为 base64 URL
我还不太明白为什么,但这里的承诺永远不会解决或拒绝。这导致我的库超时。所以也许这个策略会奏效,但我的实施存在问题。
此策略已用于库的其他领域,但 none 涉及 headless-gl 甚至 WebGL。只是二维 canvas 上下文。
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, 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, 0, this.width, this.height, format, type, 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, 0);
// flip the image
ctx.scale(1, -1);
ctx.globalCompositeOperation = 'copy';
ctx.drawImage(canvas, 0, -height, width, height);
return canvas;
}
只要您没有 alpha 或者您不关心有损 alpha,这应该可以工作。注意:代码假定您提供 unpremliplied alpha
问题是像素可能有这样的像素 255, 192, 128, 0
。但是因为 alpha 是零,当你通过上面的函数传递它时,你会在 canvas 中得到 0, 0, 0, 0
因为 canvases 总是使用预乘的 alpha。这可能不是问题,因为对于大多数用例,255, 192, 128, 0
无论如何都显示为 0,0,0,0
,但如果您有特殊用例,那么此解决方案将不起作用。
注意:您需要 the canvas package
至于您的 Image from 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 代码未提供。没有那个 header 任何 API 都无法知道数据中的内容。如果你给它 256 字节是每像素图像 8x8 4 字节吗?每像素 16x4 4 字节的图像?黑白 32x64 每像素 1 位图像?等..你需要 header.
也许编写 header 会使该代码起作用?
function convertPixelsToBMP(pixels, width, 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, width, 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;
}
注意:此代码还假设您提供 un 预乘 alpha。
@gman,谢谢你的帮助!这是有道理的,我需要 base64 URL 的 header,但我并不需要它。返回 HTMLCanvasElement
足以满足我的需要。图像中有一些 alpha,但预乘 alpha 不是问题。
我 运行 感兴趣的另一件事是生成的图像被垂直翻转。我认为这是因为 WebGL 和 2D canvas 坐标系的差异。我通过 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, 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, 0);
return canvas;
}
}