使用光浏览器JS库(如omggif)从gif中提取帧



我想从浏览器中的gif文件中提取帧。更具体地说,给定gifgifUrl: string的url,我想下载它并将其作为帧的数组imageList: ImageData[](获得。我将在画布的不同坐标处对它们使用putImageData。我也希望解决方案是轻量级的。

在BundlePhobia上,omggif的长度为50ms,可通过emerging-3G下载。到目前为止,我看到的所有替代方案都在700毫米左右。然而,omggif只提供基本的低级别交互,并且缺少常见的方法,如将gif作为ImageData数组获取。

到目前为止,我为omggif找到的最好的文档是绝对类型项目中omggif的类型。

还有movableink的例子(自2019年1月以来一直在等待公关(。

我使用TypeScript,因此如果可能的话,我对打字食谱感兴趣。

相关问题:

  • 如何使用javascript从动画gif中提取帧?[已关闭]
  • 带有帧控制的画布GIF动画

以下是您的操作方法:

import { GifReader } from 'omggif';
export const loadGifFrameList = async (
gifUrl: string,
): Promise<ImageData[]> => {
const response = await fetch(gifUrl);
const blob = await response.blob();
const arrayBuffer = await blob.arrayBuffer();
const intArray = new Uint8Array(arrayBuffer);
const reader = new GifReader(intArray as Buffer);
const info = reader.frameInfo(0);
return new Array(reader.numFrames()).fill(0).map((_, k) => {
const image = new ImageData(info.width, info.height);
reader.decodeAndBlitFrameRGBA(k, image.data as any);
return image;
});
};

如果你需要透明度,你可能想使用画布,因为它们可以与ctx.drawImage(canvas, x, y):接口

import { GifReader } from 'omggif';
export const loadGifFrameList = async (
gifUrl: string,
): Promise<HTMLCanvasElement[]> => {
const response = await fetch(gifUrl);
const blob = await response.blob();
const arrayBuffer = await blob.arrayBuffer();
const intArray = new Uint8Array(arrayBuffer);
const reader = new GifReader(intArray as Buffer);
const info = reader.frameInfo(0);
return new Array(reader.numFrames()).fill(0).map((_, k) => {
const image = new ImageData(info.width, info.height);
reader.decodeAndBlitFrameRGBA(k, image.data as any);
let canvas = document.createElement('canvas');
canvas.width = info.width;
canvas.height = info.height;
canvas.getContext('2d')!.putImageData(image, 0, 0);
return canvas;
});
};

最新更新