Please bookmark this page to avoid losing your image tool!

Image Background Eraser

(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.
/**
 * Erases the image content and fills the canvas with a solid background color.
 * The background color can be specified, or it will be auto-detected from the
 * top-left pixel of the original image.
 *
 * @param {Image} originalImg The original, loaded JavaScript Image object.
 * @param {string} [backgroundColor=''] An optional CSS color string (e.g., '#FF0000', 'blue', 'rgba(0,0,0,0.5)'). If left blank, the color of the top-left pixel of the image will be used.
 * @returns {HTMLCanvasElement} A canvas element filled with the determined background color.
 */
function processImage(originalImg, backgroundColor = '') {
  // Create a new canvas element in memory
  const canvas = document.createElement('canvas');
  const ctx = canvas.getContext('2d');

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

  // If the canvas has no size, there's nothing to do.
  if (canvas.width === 0 || canvas.height === 0) {
    return canvas;
  }
  
  let finalColor = backgroundColor;

  // Check if a background color was provided.
  // If not, we'll determine it from the image's top-left pixel.
  if (!finalColor || finalColor.trim() === '') {
    // To read pixel data, we must first draw the image onto the canvas.
    ctx.drawImage(originalImg, 0, 0);

    // Get the RGBA data for the pixel at coordinate (0, 0).
    const pixelData = ctx.getImageData(0, 0, 1, 1).data;

    // Construct a CSS rgb color string from the pixel data.
    finalColor = `rgb(${pixelData[0]}, ${pixelData[1]}, ${pixelData[2]})`;
  }

  // Set the fill style for the 2D context.
  ctx.fillStyle = finalColor;

  // Draw a filled rectangle that covers the entire canvas, effectively
  // "erasing" the content and leaving only the background color.
  ctx.fillRect(0, 0, canvas.width, canvas.height);

  // 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 Background Eraser tool allows users to remove the content of an image and fill the resulting background with a solid color. Users can specify a background color, or the tool will automatically detect and use the color of the top-left pixel of the original image. This can be particularly useful for creating images with a uniform background for graphic design, product images, or web content where a clean background is desired.

Leave a Reply

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