UNPKG

@yireen/squoosh-browser

Version:

An image compression tool run in browser while @squoosh/lib can not.

53 lines (47 loc) 1.36 kB
<!DOCTYPE html> <style> canvas { image-rendering: pixelated; } </style> <script type="module"> import imagequant from './imagequant.js'; async function loadImage(src) { // Load image const img = document.createElement('img'); img.src = src; await new Promise((resolve) => (img.onload = resolve)); // Make canvas same size as image const canvas = document.createElement('canvas'); [canvas.width, canvas.height] = [img.width, img.height]; // Draw image onto canvas const ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0); return ctx.getImageData(0, 0, img.width, img.height); } async function main() { const module = await imagequant(); console.log('Version:', module.version().toString(16)); const image = await loadImage('../example.png'); const rawImage = module.quantize( image.data, image.width, image.height, 256, 1.0, ); console.log('done'); const imageData = new ImageData( new Uint8ClampedArray(rawImage.buffer), image.width, image.height, ); const canvas = document.createElement('canvas'); canvas.width = image.width; canvas.height = image.height; const ctx = canvas.getContext('2d'); ctx.putImageData(imageData, 0, 0); document.body.appendChild(canvas); } main(); </script>