Please bookmark this page to avoid losing your image tool!

Image Black And White Converter

(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.
function processImage(originalImg, thresholdInput = 128) {
    // Validate and process the threshold parameter
    let threshold = Number(thresholdInput);
    if (isNaN(threshold) || threshold < 0 || threshold > 255) {
        console.warn(`Invalid threshold value: "${thresholdInput}". Received type: ${typeof thresholdInput}. Defaulting to 128.`);
        threshold = 128;
    }

    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d', { willReadFrequently: true }); // willReadFrequently for performance with getImageData

    // Get the natural dimensions of the image
    // These are the intrinsic dimensions of the image data
    const imgWidth = originalImg.naturalWidth;
    const imgHeight = originalImg.naturalHeight;

    // If the image hasn't loaded or has no dimensions, width/height might be 0.
    // In such a case, the canvas will be 0x0.
    if (imgWidth === 0 || imgHeight === 0) {
        console.warn("Original image has zero width or height. The resulting canvas will be empty.");
        // Setting a minimal canvas size to avoid issues if the image is truly empty.
        // However, for a black and white converter, a 0x0 canvas is a valid output for a 0x0 input.
        canvas.width = 0;
        canvas.height = 0;
        return canvas; // Return the 0x0 canvas
    }

    canvas.width = imgWidth;
    canvas.height = imgHeight;

    try {
        // Draw the original image onto the canvas
        ctx.drawImage(originalImg, 0, 0, imgWidth, imgHeight);

        // Get the pixel data from the canvas
        // This can throw a security error if the image is cross-origin and doesn't have CORS approval
        const imageData = ctx.getImageData(0, 0, imgWidth, imgHeight);
        const data = imageData.data; // This is a Uint8ClampedArray: [R, G, B, A, R, G, B, A, ...]

        // Iterate over each pixel (each pixel consists of 4 values: R, G, B, A)
        for (let i = 0; i < data.length; i += 4) {
            const r = data[i];
            const g = data[i + 1];
            const b = data[i + 2];
            // Alpha channel is data[i + 3] - we'll leave it as is.

            // Calculate grayscale value using the luminosity method (standard for perceived brightness)
            // Formula: 0.299*R + 0.587*G + 0.114*B
            const gray = 0.299 * r + 0.587 * g + 0.114 * b;

            // Apply threshold to determine if the pixel should be black or white
            let value;
            if (gray >= threshold) {
                value = 255; // White
            } else {
                value = 0;   // Black
            }

            // Set the new RGB values for the pixel
            data[i] = value;     // Red
            data[i + 1] = value; // Green
            data[i + 2] = value; // Blue
            // data[i + 3] (alpha) remains unchanged
        }

        // Put the modified image data back onto the canvas
        ctx.putImageData(imageData, 0, 0);

    } catch (e) {
        console.error("Error processing image:", e);
        // In case of an error (e.g., CORS), you might want to return the original image
        // or display an error message on the canvas.
        // For now, draw a simple error message on the canvas.
        ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear canvas
        ctx.fillStyle = 'red';
        ctx.font = '16px Arial';
        ctx.textAlign = 'center';
        ctx.fillText('Error processing image.', canvas.width / 2, canvas.height / 2);
        // If drawing text itself is problematic, return an empty canvas gracefully.
        if (canvas.width === 0 || canvas.height === 0) {
            canvas.width = 100; // Give it some dimension to show error text
            canvas.height = 30;
            ctx.fillStyle = 'red';
            ctx.font = '16px Arial';
            ctx.textAlign = 'center';
            ctx.fillText('Error.', canvas.width / 2, canvas.height / 2 + 6);
        }
    }

    return canvas;
}

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 Black And White Converter is an online tool designed to transform colored images into black and white formats. Users can upload an image and adjust the threshold value to define how brightness affects the grayscale conversion. This tool is useful for creating monochrome images for artistic effects, enhancing the contrast for better visibility in certain contexts, or preparing images for printing in black and white. It can be beneficial for photographers, graphic designers, and anyone looking to simplify the color palette of an image.

Leave a Reply

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