Converting WebP and PNG to JPG in the browser: why transparent pixels turn black
You right-click an image on a website, hit "Save image as", and get a .webp file. Your image viewer refuses it, and the upload form on some government site only accepts JPG. I build CompressPhoto, a set of free image tools that run in the browser. Converting WebP, PNG and HEIC to JPG was one of the first tools on it. The basic version is about 30 lines of JavaScript. Getting it right took a few…
When you download a .webp image from a website, it may not open correctly in some viewers, and certain government upload forms only accept JPG files. CompressPhoto is a collection of free browser-based image tools that convert WebP, PNG, and HEIC files to JPG. The basic conversion tool is a short JavaScript function that decodes the image, draws it onto a canvas, and exports the canvas as a JPEG.
However, there is a catch when dealing with transparent pixels. JPEG images do not support an alpha channel, meaning every pixel must have a solid color. When the canvas is exported as a JPEG, transparent areas are filled with black, turning transparent PNGs or WebPs into black squares. To avoid this, a white background can be painted onto the canvas before drawing the image.
This ensures transparent areas remain transparent in the exported JPG. The tool can also handle HEIC files, which require a separate decoder. It checks the file extension to determine the appropriate conversion method. The finished tool is available online and can convert up to 20 files at once, up to 30 MB each.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.