Welcome to a quick tutorial and example on how to convert the image file format in Javascript – JPG to WEBP, PNG to WEBP, JPG to PNG, and so on. Yes, you have also read correctly. We can convert an image directly in the web browser without uploading it to the server.
The general steps to convert an image in HTML and Javascript are:
- Create a file picker and empty canvas.
- On choosing a file, read it.
- Create a new image object.
- “Map” the image object onto the canvas.
- “Convert” the canvas and “force download” the image file.
It’s kind of roundabout, so read on for the exact example!
ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.
TABLE OF CONTENTS
DOWNLOAD & DEMO
Firstly, here is the download link to the example code as promised.
QUICK NOTES
If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.
SCREENSHOT
EXAMPLE CODE DOWNLOAD
Click here to download all the example source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
JAVASCRIPT CONVERT IMAGE FORMAT
All right, let us now get into more details about how the HTML Javascript image converter works.
PART 1) THE HTML
<div id="cDemo">
<label>SELECT FORMAT</label>
<select id="cFormat">
<option value="webp">WEBP</option>
<option value="jpeg">JPG</option>
<option value="png">PNG</option>
<option value="gif">GIF</option>
</select>
<label>CHOOSE FILE</label>
<input type="file" id="cFile" accept="image/*">
<label>CANVAS</label>
<canvas id="cCanvas"></canvas>
</div>
Well, don’t think this needs much explanation. Just a simple “form” with 3 “fields” –
<select id="cFormat">
Image format selector.<input type="file" id="cFile">
File picker.<canvas id="cCanvas">
The selected image will be drawn here, then “converted” and “force download”.
PART 2) JAVASCRIPT – INIT
var convert = {
// (A) PROPERTIES
hFile : null, // html file picker
hFormat : null, // html format select
hCanvas : null, // html canvas
reader : null, // file reader
ctx : null, // canvas context
// (B) INIT
init : () => {
// (B1) GET HTML ELEMENTS
convert.hFile = document.getElementById("cFile");
convert.hFormat = document.getElementById("cFormat");
convert.hCanvas = document.getElementById("cCanvas");
convert.ctx = convert.hCanvas.getContext("2d");
// (B2) LISTEN TO FILE PICKER
convert.hFile.onchange = convert.read;
},
// ...
};
window.addEventListener("load", convert.init);
When the page loads, convert.init()
will run. This pretty much gets the image format selector, file picker, canvas, and attach “read image file on pick”.
PART 3) JAVASCRIPT – READ, MAP, CONVERT, DOWNLOAD
// (C) READ SELECTED IMAGE
read : () => {
convert.reader = new FileReader();
convert.reader.onload = convert.draw;
convert.reader.readAsDataURL(convert.hFile.files[0]);
},
// (D) DRAW SELECTED IMAGE ON CANVAS
draw : () => {
let img = new Image();
img.onload = () => {
convert.hCanvas.width = img.width;
convert.hCanvas.height = img.height;
convert.ctx.drawImage(img, 0, 0);
convert.go();
};
img.src = convert.reader.result;
},
// (E) CONVERT & "FORCE DOWNLOAD"
go : () => {
let a = document.createElement("a"),
f = convert.hFormat.value;
a.href = convert.hCanvas.toDataURL(`image/${f}`);
if (f=="jpeg") { f = "jpg"; }
a.download = `converted.${f}`;
a.click();
a.remove();
}
Not going to explain line-by-line, very boring… But once you trace through, this “waterfall process” is long-winded but pretty straightforward.
convert.read()
Will run when the user chooses an image file. We create aFileReader
to read the selected file.convert.draw()
When theFileReader
is ready, we create anImage
object from the selected file and “map” it onto the HTML canvas.convert.go()
“Convert” the canvas and “force download”. Please take note that programmatically clicking on an anchor linka.click()
may not always work. It may be a better idea to attach the link to a button on the page and let the user manually click on it.
EXTRA BITS & LINKS
That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.
COMPATIBILITY CHECKS
- Arrow Functions – CanIUse
- File Reader – CanIUse
- Canvas – CanIUse
This example works on all modern “Grade A” browsers.
LINKS & REFERENCES
- Download HTML Canvas As Image – Code Boxx
- How To Read Files In Javascript – Code Boxx
- Example on CodePen – JS File Image Format Converter
THE END
Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!