Please bookmark this page to avoid losing your image tool!

Image To Black And White Binary 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.
/**
 * Converts an image to a black and white binary representation based on a brightness threshold.
 *
 * @param {HTMLImageElement} originalImg The original image object to be processed.
 * @param {number} threshold A value between 0 and 255. Pixels brighter than this value will become white, and others will become black. Defaults to 128.
 * @returns {HTMLCanvasElement} A new canvas element displaying the black and white binary image.
 */
function processImage(originalImg, threshold = 128) {
  // Create a new canvas element
  const canvas = document.createElement('canvas');
  const ctx = canvas.getContext('2d');

  // Set the canvas dimensions to match the original image
  canvas.width = originalImg.naturalWidth;
  canvas.height = originalImg.naturalHeight;

  // Draw the original image onto the canvas
  ctx.drawImage(originalImg, 0, 0, canvas.width, canvas.height);

  // Get the pixel data from the canvas
  const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
  const data = imageData.data;

  // Ensure the threshold is within the valid range [0, 255]
  const validThreshold = Math.max(0, Math.min(255, threshold));

  // Iterate over each pixel (R, G, B, A)
  for (let i = 0; i < data.length; i += 4) {
    const red = data[i];
    const green = data[i + 1];
    const blue = data[i + 2];

    // Calculate the brightness of the pixel using the luminosity method
    // Formula: 0.299*R + 0.587*G + 0.114*B
    const brightness = 0.299 * red + 0.587 * green + 0.114 * blue;

    // Determine the new color (black or white) based on the threshold
    const newColor = brightness > validThreshold ? 255 : 0;

    // Set the pixel to the new color
    data[i] = newColor;     // Red
    data[i + 1] = newColor; // Green
    data[i + 2] = newColor; // Blue
    // The alpha channel (data[i + 3]) is left unchanged (fully opaque)
  }

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

  // Return the resulting canvas
  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 To Black And White Binary Converter is a tool that transforms an image into a black and white binary representation, allowing users to simplify images by applying a brightness threshold. Pixels that exceed the specified threshold become white, while those below it turn black. This tool is useful for various applications, including creating high-contrast images for print, preparing images for optical character recognition (OCR), and enhancing graphical elements in design projects.

Leave a Reply

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