Skip to content

Make images smaller using best-in-class codecs, right in the browser.

JavaScript
1.3 KB
Raw Blame
<!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>