FROMDEV

How to Convert a WebP Image to a JPEG in the Browser using JavaScript

JPG image

WebP is a modern image format that provides superior compression for images on the web. However, not all browsers and systems support WebP, so you might need to convert WebP images to the more universally supported JPEG format. This tutorial will guide you through converting a WebP image to a JPEG image directly in the browser using JavaScript.

Prerequisites

Steps to Convert WebP to JPEG

  1. Create an HTML File
  2. Set Up the JavaScript Function
  3. Load and Convert the Image
  4. Display the Converted Image

1. Create an HTML File

First, create an HTML file where we will include our JavaScript code and display the images.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Convert WebP to JPEG</title>
</head>
<body>
    <h1>Convert WebP to JPEG</h1>
    <input type="file" id="upload" accept="image/webp">
    <br><br>
    <img id="originalImage" alt="Original WebP Image" style="max-width: 100%; display: none;">
    <br><br>
    <img id="convertedImage" alt="Converted JPEG Image" style="max-width: 100%; display: none;">
    <script src="script.js"></script>
</body>
</html>

This HTML file includes an input element for uploading a WebP image and two image elements to display the original and converted images.

2. Set Up the JavaScript Function

Create a JavaScript file named script.js and add the following code:

function convertWebPToJPG(webpUrl, callback) {
    // Create an image element
    const img = new Image();
    
    // Set crossOrigin to allow cross-origin image loading
    img.crossOrigin = 'Anonymous';
    
    // When the image is loaded
    img.onload = () => {
        // Create a canvas element
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        
        // Set canvas dimensions to the image dimensions
        canvas.width = img.width;
        canvas.height = img.height;
        
        // Draw the image onto the canvas
        ctx.drawImage(img, 0, 0);
        
        // Get the data URL of the canvas as JPEG
        const jpgDataUrl = canvas.toDataURL('image/jpeg');
        
        // Call the callback function with the JPEG data URL
        callback(jpgDataUrl);
    };
    
    // Set the image source to the WebP URL
    img.src = webpUrl;
}

3. Load and Convert the Image

Next, add the code to handle the image upload and conversion process:

document.getElementById('upload').addEventListener('change', function(event) {
    const file = event.target.files[0];
    if (file && file.type === 'image/webp') {
        const reader = new FileReader();
        reader.onload = function(e) {
            const webpUrl = e.target.result;
            
            // Display the original WebP image
            const originalImage = document.getElementById('originalImage');
            originalImage.src = webpUrl;
            originalImage.style.display = 'block';
            
            // Convert the WebP image to JPEG
            convertWebPToJPG(webpUrl, (jpgDataUrl) => {
                // Display the converted JPEG image
                const convertedImage = document.getElementById('convertedImage');
                convertedImage.src = jpgDataUrl;
                convertedImage.style.display = 'block';
            });
        };
        reader.readAsDataURL(file);
    } else {
        alert('Please upload a WebP image.');
    }
});

This code sets up an event listener on the file input element. When a WebP image is selected, it reads the file as a data URL, displays the original WebP image, and then converts it to a JPEG image, displaying the result.

4. Display the Converted Image

Finally, when the conversion is done, the original and converted images are displayed on the webpage.

Full Code

Here is the complete code combining all the steps:

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Convert WebP to JPEG</title>
</head>
<body>
    <h1>Convert WebP to JPEG</h1>
    <input type="file" id="upload" accept="image/webp">
    <br><br>
    <img id="originalImage" alt="Original WebP Image" style="max-width: 100%; display: none;">
    <br><br>
    <img id="convertedImage" alt="Converted JPEG Image" style="max-width: 100%; display: none;">
    <script src="script.js"></script>
</body>
</html>

script.js

function convertWebPToJPG(webpUrl, callback) {
    // Create an image element
    const img = new Image();
    
    // Set crossOrigin to allow cross-origin image loading
    img.crossOrigin = 'Anonymous';
    
    // When the image is loaded
    img.onload = () => {
        // Create a canvas element
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        
        // Set canvas dimensions to the image dimensions
        canvas.width = img.width;
        canvas.height = img.height;
        
        // Draw the image onto the canvas
        ctx.drawImage(img, 0, 0);
        
        // Get the data URL of the canvas as JPEG
        const jpgDataUrl = canvas.toDataURL('image/jpeg');
        
        // Call the callback function with the JPEG data URL
        callback(jpgDataUrl);
    };
    
    // Set the image source to the WebP URL
    img.src = webpUrl;
}

document.getElementById('upload').addEventListener('change', function(event) {
    const file = event.target.files[0];
    if (file && file.type === 'image/webp') {
        const reader = new FileReader();
        reader.onload = function(e) {
            const webpUrl = e.target.result;
            
            // Display the original WebP image
            const originalImage = document.getElementById('originalImage');
            originalImage.src = webpUrl;
            originalImage.style.display = 'block';
            
            // Convert the WebP image to JPEG
            convertWebPToJPG(webpUrl, (jpgDataUrl) => {
                // Display the converted JPEG image
                const convertedImage = document.getElementById('convertedImage');
                convertedImage.src = jpgDataUrl;
                convertedImage.style.display = 'block';
            });
        };
        reader.readAsDataURL(file);
    } else {
        alert('Please upload a WebP image.');
    }
});
Exit mobile version