Dev.to WebDev πŸ›  Dev πŸ‘ 0 πŸ“– 4 min read

Image Compress Workflow: Fit an Avatar Under 200 KiB in the Browser

Your avatar upload limit is 200 KiB. A photo taken on a phone can be much larger, even if it looks small inside the profile form. Setting width: 128px makes the preview narrower; it doesn't change the bytes that get uplo

Your avatar upload limit is 200 KiB. A photo taken on a phone can be much larger, even if it looks small inside the profile form. Setting width: 128px makes the preview narrower; it doesn't change the bytes that get uploaded.

Here's a local JavaScript workflow that measures the encoded file before offering it for download. It resizes from the original bitmap, tries a few JPEG quality settings, and only returns a file that actually fits the cap.

Set a byte limit, not just a quality setting

In this example, 200 KiB means 204,800 bytes. If your endpoint says 200 KB and uses decimal units, use 200,000 instead. Check whether the limit applies to the image itself or the entire request: multipart boundaries and other form fields also use bytes.

Canvas takes a quality hint between 0 and 1, but the hint isn't a target size. Two photos exported at the same quality can still have very different byte counts. Use blob.size to decide whether to accept the result.

Compress a still photo in the browser

Save this example as avatar-demo.html and open it in a modern browser. It accepts JPEG and PNG inputs and exports JPEG. It doesn't upload the selected photo.

<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>Avatar byte budget demo</title>
<label for="photo">Select a JPEG or PNG</label>
<input id="photo" type="file" accept="image/jpeg,image/png">
<p id="status" role="status"></p>
<a id="download" download="avatar.jpg" hidden>Download JPEG</a>

<script type="module">
  const maxBytes = 200 * 1024;
  const edgeLengths = [1024, 768, 512, 384, 256];
  const qualities = [0.88, 0.76, 0.64];
  const allowedTypes = new Set(['image/jpeg', 'image/png']);

  function encodeJpeg(canvas, quality) {
    return new Promise((resolve, reject) => {
      canvas.toBlob(blob => {
        if (!blob || blob.type !== 'image/jpeg') {
          reject(new Error('The browser could not encode a JPEG.'));
          return;
        }
        resolve(blob);
      }, 'image/jpeg', quality);
    });
  }

  async function compressAvatar(file) {
    if (!allowedTypes.has(file.type)) {
      throw new Error('Select a JPEG or PNG.');
    }

    const bitmap = await createImageBitmap(file);
    const canvas = document.createElement('canvas');

    try {
      const context = canvas.getContext('2d');
      if (!context) throw new Error('Canvas is unavailable.');

      let previousSize = '';
      for (const edge of edgeLengths) {
        const scale = Math.min(1, edge / Math.max(bitmap.width, bitmap.height));
        const width = Math.max(1, Math.round(bitmap.width * scale));
        const height = Math.max(1, Math.round(bitmap.height * scale));
        const sizeKey = width + 'x' + height;
        if (sizeKey === previousSize) continue;
        previousSize = sizeKey;

        canvas.width = width;
        canvas.height = height;
        context.fillStyle = '#fff';
        context.fillRect(0, 0, width, height);
        context.drawImage(bitmap, 0, 0, width, height);

        for (const quality of qualities) {
          const blob = await encodeJpeg(canvas, quality);
          if (blob.size <= maxBytes) return { blob, width, height, quality };
        }
      }

      throw new Error('None of the tested settings fit the byte limit.');
    } finally {
      bitmap.close();
      canvas.width = canvas.height = 1;
    }
  }

  const input = document.querySelector('#photo');
  const status = document.querySelector('#status');
  const link = document.querySelector('#download');
  let downloadUrl;

  input.addEventListener('change', async () => {
    const file = input.files[0];
    if (!file) return;

    link.hidden = true;
    link.removeAttribute('href');
    if (downloadUrl) URL.revokeObjectURL(downloadUrl);
    input.disabled = true;
    status.textContent = 'Compressing…';

    try {
      const { blob, width, height } = await compressAvatar(file);
      downloadUrl = URL.createObjectURL(blob);
      link.href = downloadUrl;
      link.hidden = false;
      status.textContent = blob.size.toLocaleString() + ' bytes Β· '
        + width + ' Γ— ' + height + ' px';
    } catch (error) {
      status.textContent = error.message || 'Could not process this photo.';
    } finally {
      input.disabled = false;
      input.value = '';
    }
  });
</script>

The loop tries higher quality first at each size, then drops to a smaller image if none of those encodes fits. It favors dimensions over quality within the tested settings; it doesn't claim to find the best-looking JPEG. Each attempt uses the original decoded image, not a previous JPEG export.

The white fill is deliberate: JPEG doesn't preserve transparency. If you need transparent icons, don't send them through this avatar preset. The MIME type check is deliberate too: the Canvas standard allows an unsupported requested format to fall back to PNG, which you shouldn't save with a .jpg filename.

Optional online workflow

For a photo you're comfortable uploading to an external service, ImageCompress is another option for preparing a compressed copy. Check the downloaded file against the same 204,800-byte limit and preview it in the avatar slot. The local demo above doesn't depend on that service.

Check the output in the actual avatar slot

Try one ordinary portrait and one detailed photo with hair, glasses, or a busy background. Open the exported JPEG in the same size and crop used by your profile page. A file can pass the byte check and still look bad inside a 96-pixel circle. If your product requires a square crop, crop first and then run the size and quality loop.

This demo decodes the source at full size, so very large photos can still use a lot of memory before resizing. In a real uploader, handle decode failures, guard against oversized inputs, and enforce the upload limit on the server too; checking the file in the browser is for immediate feedback, not server-side validation.

The useful distinction is quality is a knob; bytes are the check. If none of the tested settings meets your requirements, report that result rather than silently uploading an oversized or unreadable image.

πŸ“° Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.