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

问题描述 投票:0回答:1

我想从浏览器中的gif文件中提取帧。更具体地说,给定gif gifUrl: string的网址,我想下载它并将其作为帧数组imageList: ImageData[]获得。我将在画布的各个坐标上对它们使用putImageData。我也希望该解决方案轻巧。

BundlePhobia上,omggif长度为50ms,可以通过新兴的3G下载。到目前为止,我所看到的所有替代方案都在700ms左右。但是,omggif仅提供基本的低级交互,并且缺少常见的食谱,例如将gif作为ImageData数组获取。

到目前为止,我发现的有关omggif的最佳文档是omggif's types in the DefinitelyTyped project

还有movableink's example(自2019年1月以来正在接受公关。

我使用TypeScript,因此对键入的配方感兴趣,如果可能。

相关问题:

javascript typescript frame gif
1个回答
0
投票

这是您的操作方式:

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;
    });
};
© www.soinside.com 2019 - 2024. All rights reserved.