How to Convert Images to WebP Using JavaScript (Beginner's Guide)

← Prev

WebP is a modern image format developed by Google that provides better compression than traditional image formats such as JPEG and PNG. It helps reduce image file sizes while maintaining good visual quality.

Smaller images can improve website loading speed, reduce bandwidth consumption, and contribute to a better user experience.

In this tutorial, we will learn how to create a simple image-to-WebP converter using HTML and JavaScript. The best part is that we don't need any external libraries, server-side processing, or third-party APIs. Everything happens directly inside the user's browser.

The HTML and the Script

<body>
    <input type="file" id="imageInput" accept="image/*">
    <button onclick="convertToWebP()">Save as WebP</button>
</body>

<script>
    async function convertToWebP() {
        const input = document.getElementById("imageInput");
        const file = input.files[0];

        if (!file) {
            alert("Please select an image first.");
            return;
        }

        const img = new Image();
        img.src = URL.createObjectURL(file);

        await img.decode();

        const canvas = document.createElement("canvas");
        canvas.width = img.naturalWidth;
        canvas.height = img.naturalHeight;

        const ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0);

        canvas.toBlob(
            (blob) => {
                if (!blob) {
                    alert("WebP conversion failed.");
                    return;
                }

                const url = URL.createObjectURL(blob);
                const a = document.createElement("a");

                a.href = url;
                a.download = file.name.replace(/\.[^.]+$/, "") + ".webp";
                a.click();

                URL.revokeObjectURL(url);
                URL.revokeObjectURL(img.src);
            },
            "image/webp",
            0.85,
        );
    }
</script>
Try it

The HTML section has a simple interface that allows users to select an image and convert the image into WebP format.

In the "script" section, first we'll check whether the user has selected a file.

if (!file) {
    alert('Please select an image first.');
    return;
}

Next, it will load the image.

const img = new Image();
img.src = URL.createObjectURL(file);

await img.decode();

This piece of code await img.decode(); waits for the image to load. This is important, in case the image is big and we can draw the image into a canvas before it has loaded.

The decode() method returns a Promise that resolves when the image has been decoded and is ready for use.

The await keyword makes JavaScript wait for this operation to complete before moving to the next statement.

Now comes the most important part of the conversion process. We'll create a canvas element. Its a drawing area that JavaScript can use to display and manipulate images, graphics, and other visual elements.

const canvas = document.createElement('canvas');

canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;

Finally, we'll convert the image to WebP format.

canvas.toBlob((blob) => {
    if (!blob) {
        alert('WebP conversion failed.');
        return;
    }
}, 'image/webp', 0.85);

The canvas.toBlob() method converts the canvas content into a Blob object. A Blob (Binary Large Object) represents binary data, such as an image file.

The method accepts three arguments.

So, 'image/webp' tells the browser to generate WebP image.

The third argument is 0.85. This represents "85%" image quality. You can assign values like "1.0" (it is the highest quality), 0.85, 0.75, 0.60 etc.

Once the processing is complete, it will download the image.

← Previous