Please bookmark this page to avoid losing your image tool!

Image Format Changer

(Free & Supports Bulk Upload)

Drag & drop your images here or

The result will appear here...
You can edit the below JavaScript code to customize the image tool.
async function processImage(originalImg, targetFormat = "png", quality = 0.92) {
    // Step 1: Ensure the original image is loaded and valid.
    // The Image object might be created but its source not yet loaded, or failed to load.
    if (!originalImg.complete) {
        try {
            // Wait for the image to load if it's not already complete.
            // This promise handles the asynchronous nature of image loading.
            await new Promise((resolve, reject) => {
                // If originalImg.src is not set or is invalid, 'complete' might be true
                // and naturalWidth/Height 0, which is caught by the check below.
                // If loading is genuinely in progress, onload/onerror will fire.
                originalImg.onload = resolve;
                originalImg.onerror = () => reject(new Error("Original image could not be loaded. Check its source or network."));
            });
        } catch (e) {
             // Rethrow the error from the promise.
             throw e;
        }
    }

    // After attempting to load (or if already complete), check dimensions.
    // A naturalWidth or naturalHeight of 0 means the image is invalid, corrupted,
    // not an image, or its src was never set or was invalid.
    if (originalImg.naturalWidth === 0 || originalImg.naturalHeight === 0) {
        throw new Error("Original image has zero dimensions. It might be an invalid image format, corrupted, or the source URL is incorrect/missing.");
    }

    // Step 2: Create a canvas element to draw the image.
    const canvas = document.createElement('canvas');
    canvas.width = originalImg.naturalWidth;
    canvas.height = originalImg.naturalHeight;

    const ctx = canvas.getContext('2d');
    // Draw the original image onto the canvas.
    // If originalImg is an animated GIF, only the first frame will be drawn.
    ctx.drawImage(originalImg, 0, 0, originalImg.naturalWidth, originalImg.naturalHeight);

    // Step 3: Determine the MIME type for the target format.
    let lcFormat = String(targetFormat).toLowerCase(); // Ensure targetFormat is a string and lowercase for reliable comparison.
    let mimeType;

    switch (lcFormat) {
        case 'png':
            mimeType = 'image/png';
            break;
        case 'jpg': // 'jpg' is a common alias for 'jpeg'.
        case 'jpeg':
            mimeType = 'image/jpeg';
            break;
        case 'webp':
            mimeType = 'image/webp';
            break;
        case 'gif':
            // Note: canvas.toDataURL('image/gif') typically produces a static GIF (first frame only).
            mimeType = 'image/gif';
            break;
        // Formats like BMP, TIFF, ICO are not natively supported by canvas.toDataURL in most browsers.
        // Supporting them would require external libraries or more complex implementations.
        default:
            // For any other format string, attempt to use it directly.
            // This allows for potential future support or browser-specific formats (e.g., 'image/avif').
            // If the browser doesn't support it, canvas.toDataURL will likely throw an error or return a minimal data URL.
            console.warn(`Format "${targetFormat}" is not explicitly handled. Attempting to use "image/${lcFormat}". This may fail if the browser does not support this MIME type for canvas.toDataURL.`);
            mimeType = `image/${lcFormat}`;
    }

    // Step 4: Convert the canvas content to a Data URL in the target format.
    let dataURL;
    try {
        if (mimeType === 'image/jpeg' || mimeType === 'image/webp') {
            // These formats support a quality setting (0.0 to 1.0).
            let q = Number(quality);
            if (isNaN(q) || q < 0 || q > 1) {
                // If quality is invalid (e.g., not a number, or out of range), use a sensible default and warn the user.
                console.warn(`Invalid quality value: "${quality}". Must be a number between 0.0 and 1.0. Using default 0.92.`);
                q = 0.92;
            }
            dataURL = canvas.toDataURL(mimeType, q);
        } else {
            // For formats like PNG and GIF, the quality parameter is ignored by toDataURL.
            dataURL = canvas.toDataURL(mimeType);
        }
    } catch (e) {
        // This error can occur if the MIME type itself is malformed or not recognized at all by the browser's canvas implementation.
        throw new Error(`Failed to convert canvas to Data URL for format "${targetFormat}" (MIME type "${mimeType}"): ${e.message || e}`);
    }

    // Some browsers might return "data:," for unsupported types instead of throwing an error.
    // Check for this minimal, effectively empty Data URL.
    if (!dataURL || dataURL === "data:,") {
        throw new Error(`Conversion to format "${targetFormat}" (MIME type "${mimeType}") resulted in empty or invalid image data. The format might not be supported by your browser's canvas.toDataURL method.`);
    }

    // Step 5: Create a new Image object and set its source to the Data URL.
    // The function returns a Promise that resolves with this new Image object once it's loaded.
    // This ensures the caller receives a fully usable image.
    const newImg = new Image();
    return new Promise((resolve, reject) => {
        newImg.onload = () => resolve(newImg);
        newImg.onerror = (eventError) => {
            // An error here means the browser failed to load the image from the generated Data URL.
            // This could be due to an excessively large Data URL, a corrupted Data URL, or browser limitations.
            // eventError is an Event object, not an Error, so it lacks a .message property.
            console.error("Error event object during new image load:", eventError);
            reject(new Error(`Failed to load the converted image from Data URL for format "${targetFormat}". The generated Data URL might be malformed, too large, or the format (though valid for Data URL creation) is not supported by the <img> element.`));
        };
        newImg.src = dataURL;
    });
}

Free Image Tool Creator

Can't find the image tool you're looking for?
Create one based on your own needs now!

Description

The Image Format Changer is a versatile online tool designed to convert images from one format to another. It supports popular formats such as PNG, JPEG, WebP, and GIF, allowing users to adapt images for various needs such as web optimization, printing, or sharing across different platforms. By adjusting the quality parameter, users can also manage file size versus image quality. This tool is ideal for graphic designers, web developers, and anyone needing to upload or display images in specific formats without compromising on ease of use.

Leave a Reply

Your email address will not be published. Required fields are marked *