Last active
September 12, 2023 06:29
-
-
Save spd789562/7eb12dc22c1dde8cd68d945ec9968f45 to your computer and use it in GitHub Desktop.
using node-webpmux in browser
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import WebP from 'node-webpmux'; // remember put libwebp.wasm somewhere | |
import { Buffer } from 'buffer'; | |
function createColorCanvasArrayBuffer(width: number, height: number, color: string) { | |
const canvas = document.createElement('canvas'); | |
canvas.width = width; | |
canvas.height = height; | |
const ctx = canvas.getContext('2d')!; | |
ctx.fillStyle = color; | |
ctx.fillRect(0, 0, width, height); | |
return ctx.getImageData(0, 0, width, height).data.buffer; | |
} | |
async function getImageFromBuffer(buff, width, height) { | |
const image = await WebP.Image.getEmptyImage(); | |
await image.setImageData(buff, { width, height }); | |
return image; | |
} | |
async function init() { | |
await WebP.Image.initLib(); | |
const width = 300; | |
const height = 300; | |
// or using fetch for existen image `await fetch(testImage).then((res) => res.arrayBuffer())` | |
const redBuffer = Buffer.from(createColorCanvasArrayBuffer(width, height, 'red')); | |
const greenBuffer = Buffer.from(createColorCanvasArrayBuffer(width, height, 'green')); | |
// create empty animate image | |
const aniImg = await WebP.Image.getEmptyImage(); | |
aniImg.convertToAnim(); | |
// generate frame | |
const frames = await Promise.all([ | |
WebP.Image.generateFrame({ img: await getImageFromBuffer(redBuffer, width, height), delay: 1000, x: 0, y: 0 }), | |
WebP.Image.generateFrame({ img: await getImageFromBuffer(greenBuffer, width, height), delay: 1000, x: 0, y: 0 }), | |
]); | |
aniImg.frames.push(...frames); | |
const resultArrBuff = await WebP.Image.save(null, { frames, width, height }); | |
const img = new Image(); | |
img.src = `data:image/webp;base64,${resultArrBuff.toString('base64')}`; | |
document.body.appendChild(img); | |
} | |
init(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment