|
| 1 | +/* eslint-disable no-console */ |
| 2 | +import { createReadStream } from 'node:fs' |
| 3 | +import { join } from 'node:path' |
| 4 | +import { argv } from 'node:process' |
| 5 | +import JsGifEncoder from 'gif-encoder-2' |
| 6 | +import { PNG } from 'pngjs' |
| 7 | +import { GIFEncoder } from '../../index.mjs' |
| 8 | + |
| 9 | +const imagePaths = [...Array(46).keys()].map((i) => `../BBB${i + 1580}.png`) |
| 10 | + |
| 11 | +async function loadImage(path) { |
| 12 | + return new Promise((resolve, reject) => { |
| 13 | + createReadStream(path) |
| 14 | + .pipe(new PNG()) |
| 15 | + .on('parsed', function () { |
| 16 | + resolve({ |
| 17 | + buffer: this.data, |
| 18 | + width: this.width, |
| 19 | + height: this.height, |
| 20 | + }) |
| 21 | + }) |
| 22 | + .on('error', reject) |
| 23 | + }) |
| 24 | +} |
| 25 | + |
| 26 | +async function loadImages() { |
| 27 | + const promises = imagePaths.map(loadImage) |
| 28 | + return await Promise.all(promises) |
| 29 | +} |
| 30 | + |
| 31 | +async function main() { |
| 32 | + const images = await loadImages() |
| 33 | + try { |
| 34 | + const encoder = new GIFEncoder(images[0].width, images[0].height, join(import.meta.dirname, 'output.gif')) |
| 35 | + encoder.setFrameRate(30) |
| 36 | + encoder.setSampleFactor(2) |
| 37 | + // encoder.setRepeat(0) |
| 38 | + for (const image of images) { |
| 39 | + encoder.addFrame(image.buffer) |
| 40 | + } |
| 41 | + console.log('Encoding with Rust GIF encoder') |
| 42 | + const start = new Date().getTime() |
| 43 | + await encoder.finish() |
| 44 | + const end = new Date().getTime() |
| 45 | + console.log(`Encode time: ${end - start}ms`) |
| 46 | + } catch (error) { |
| 47 | + console.error(`Unexpected error: ${JSON.stringify(error)}`) |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +class ContextLike { |
| 52 | + constructor(buffer) { |
| 53 | + this.buffer = buffer |
| 54 | + } |
| 55 | + |
| 56 | + getImageData(sx, sy, sw, sh) { |
| 57 | + return { data: this.buffer } |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +async function mainJs() { |
| 62 | + const images = await loadImages() |
| 63 | + const gif = new JsGifEncoder(images[0].width, images[1].height, 'neuquant', true, 46) |
| 64 | + gif.setFrameRate(30) |
| 65 | + gif.setRepeat(1) |
| 66 | + console.log('Encoding with JavaScript GIF encoder') |
| 67 | + const start = new Date().getTime() |
| 68 | + gif.start() |
| 69 | + for (const image of images) { |
| 70 | + gif.addFrame(new ContextLike(image)) |
| 71 | + } |
| 72 | + gif.finish() |
| 73 | + const end = new Date().getTime() |
| 74 | + console.log(`Encode time: ${end - start}ms`) |
| 75 | +} |
| 76 | + |
| 77 | +if (argv.includes('--js')) { |
| 78 | + mainJs() |
| 79 | +} else { |
| 80 | + main() |
| 81 | +} |
0 commit comments