DEV Community

David Miller
David Miller

Posted on

How to verify a HEIC-to-JPEG conversion before upload

An HEIC converter can return successfully while a browser preview or thumbnail service still refuses the result. The app may even have named the output photo.jpg. Before upload, inspect the bytes that came back.

Check the result in the browser

If your converter returns a Blob, this function rejects an empty file, checks the first two bytes for a JPEG marker, and asks the browser to decode the image.

async function inspectJpeg(blob) {
  if (!blob || blob.size === 0) {
    throw new Error("The converter returned an empty file");
  }

  const header = new Uint8Array(await blob.slice(0, 2).arrayBuffer());
  if (header[0] !== 0xff || header[1] !== 0xd8) {
    throw new Error("The output does not start with a JPEG marker");
  }

  const image = await createImageBitmap(blob);
  try {
    if (image.width === 0 || image.height === 0) {
      throw new Error("The decoded image has no dimensions");
    }
    return { width: image.width, height: image.height, bytes: blob.size };
  } finally {
    image.close();
  }
}
Enter fullscreen mode Exit fullscreen mode

The marker check rejects many wrong-format files, but those two bytes can also be present in a truncated JPEG. Decoding catches more failures. Even a file that passes both checks may have the wrong orientation or colors, or may have lost transparency or metadata during conversion. Check those properties with sample photos.

The filename and Blob.type are useful hints, but neither verifies the bytes. MDN explains why Blob.type cannot be the only validation check. The file input's accept attribute only guides the picker; it doesn't validate the selected file. Validate uploads again on the server.

Watch for a canvas fallback

A canvas conversion has one easy-to-miss case. If you call canvas.toBlob(callback, "image/jpeg") and the browser doesn't support the requested format, it exports PNG instead. If the app still gives that blob a .jpg name, the extension disagrees with the file. The check above catches that mismatch.

Keep a few awkward test photos

Use a portrait photo whose orientation matters and an image where a color shift would be visible. A multi-image HEIC and a damaged file are useful too. Check the decoded dimensions and look at the output. The smoke test won't tell you whether the chosen image, its colors, or its metadata match the original.

For a manual comparison, you can try Morphio's HEIC-to-JPG converter with the same samples. Morphio is my product; the browser check above works with any converter.

Top comments (0)