Build a White Background Remover From PNG,JPEG Images in Browser Using HTML5 CSS3 and Javascript Full Project For Beginners

 

 

index.html

 

 

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.0.3/tailwind.min.css">
  <link rel="stylesheet"
    href="https://cdnjs.cloudflare.com/ajax/libs/simple-line-icons/2.5.5/css/simple-line-icons.min.css">
  <link rel="preconnect" href="https://fonts.gstatic.com">
  <link href="https://fonts.googleapis.com/css2?family=DotGothic16&display=swap" rel="stylesheet">
  <title>White Background Image Remover</title>
  <meta name="description" content="An easy and fast way to remove the white background from an image and delivery a PNG image as result.">
  <meta name="keywords" content="white, background, remover, easy, fast, PNG">
  <style type="text/css">
    html, body{
      font-family: 'DotGothic16', sans-serif;
    }
</style>  
</head>
<body class="w-screen h-screen flex flex-col justify-start items-center bg-blue-300">
  <header class="mt-10 mb-10 text-center">
    <h1 class="text-5xl font-extrabold">White Background Remover</h1>
    <h2 class="leading-8 mt-2 max-w-xl">An easy and fast way to remove the white background from an image and delivery a PNG image as result</h2>
  </header>
  <form action="#" id="image-form" enctype="multipart/form-data" class="border-2">
    <input type="file" name="image-input" id="image-input" class="w-0 h-0">
    <label for="image-input" id="image-label" class="cursor-pointer pl-16 pr-16">Click here to image upload</label>
    <button class="pt-2 pb-2 pl-10 pr-10 bg-gray-400 hover:bg-blue-200 transition-all duration-300" type="submit">Remove Background</button>
  </form>
  <div id="preview-section" class="mt-10">
    <div class="preview-original-image"></div>
    <canvas id="canvas"></canvas>
  </div>
  <a id="download-button" download="image-with-removed-white-bg.png" class="fixed right-10 top-12 bg-yellow-300 hover:bg-yellow-400 cursor-pointer transition-all duration-300 pl-12 pr-12 pt-10 pb-10 shadow">
    <span type="button" class="text-2xl uppercase">Download</span>
    <span class="icon-arrow-down-circle text-2xl"></span>
  </a>
  <script>
    const ORIGINAL_IMAGE_ID = "original-img";
const CANVAS_ID = "canvas";
const FORM_ID = "image-form";
const DOWNLOAD_BUTTON_ID = "download-button";
const IMAGE_INPUT_ID = "image-input";
const IMAGE_LABEL_ID = "image-label";

window.onload = () => {
  Listeners.inputFileChange(IMAGE_INPUT_ID, IMAGE_LABEL_ID);
  Listeners.formSubmit(FORM_ID);
  Listeners.downloadButton(DOWNLOAD_BUTTON_ID, ORIGINAL_IMAGE_ID, CANVAS_ID);
};

const Listeners = {
  formSubmit: (formId) => {
    const form = document.getElementById(formId);
    form.addEventListener("submit", (formEvent) => {
      formEvent.preventDefault();
      ImageProcessor.getImageDataFromInputFile("#image-form input[type=file]")
        .then((imageData) => ImageProcessor.getImageObject(imageData))
        .then((imageObject) =>
          ImageProcessor.createPreviewAndCanvas(
            imageObject,
            ORIGINAL_IMAGE_ID,
            CANVAS_ID,
            ImageProcessor.drawImageOnCanvas
          )
        );
    });
  },
  downloadButton: (downloadButtonId, originalImageId, canvasId) => {
    const downloadButtonElement = document.getElementById(downloadButtonId);
    const canvasElement = document.getElementById(canvasId);
    downloadButtonElement.addEventListener("click", (event) => {
      const originalImage = document.getElementById(originalImageId);
      if (!originalImage) event.preventDefault();
      const imageToDownload = canvasElement
        .toDataURL("image/png")
        .replace("image/png", "image/octet-stream");
      downloadButtonElement.setAttribute("href", imageToDownload);
    });
  },
  inputFileChange: (imageInputId, imageLabelId) => {
    const input = document.getElementById(imageInputId);
    input.addEventListener("change", (event) => {
      const label = document.getElementById(imageLabelId);
      label.innerText = event.target.files[0].name;
    });
  },
};

const ImageProcessor = {
  getImageDataFromInputFile: (query) => {
    const imageData = document.querySelector(query).files[0];
    return new Promise((resolve) => resolve(imageData));
  },
  getImageObject: (imageData) => {
    const fileReader = new FileReader();
    const imageObject = new Image();
    fileReader.readAsDataURL(imageData);
    fileReader.onload = (event) => {
      imageObject.src = event.target.result;
    };
    return new Promise((resolve) => resolve(imageObject));
  },
  createPreviewAndCanvas: (imageObject, imageId, canvasId, canvasCallback) => {
    const imageElement = document.createElement("img");
    imageObject.onload = () => {
      const oldImage = document.getElementById(imageId);
      if (oldImage) {
        oldImage.remove();
      }
      imageElement.src = imageObject.src;
      imageElement.width = imageObject.width;
      imageElement.height = imageObject.height;
      imageElement.id = imageId;
      imageElement.className = "hidden";

      document
        .querySelector(".preview-original-image")
        .appendChild(imageElement);

      canvasCallback(canvasId, imageId);
    };

    return new Promise((resolve) => resolve());
  },
  drawImageOnCanvas: (canvasElementId, originalImageElementId) => {
    const canvas = document.getElementById(canvasElementId),
      originalImage = document.getElementById(originalImageElementId),
      canvasContext = canvas.getContext("2d");

    canvas.height = originalImage.height;
    canvas.width = originalImage.width;
    canvasContext.drawImage(originalImage, 0, 0);

    const imageData = canvasContext.getImageData(
        0,
        0,
        originalImage.width,
        originalImage.height
      ),
      pixels = imageData.data,
      transparency = { r: 0, g: 0, b: 0, a: 0 };

    for (
      let cursor = 0, totalOfPixels = pixels.length;
      cursor < totalOfPixels;
      cursor += 4
    ) {
      let r = pixels[cursor],
        g = pixels[cursor + 1],
        b = pixels[cursor + 2];

      if (r === 255 && g === 255 && b === 255) {
        pixels[cursor] = transparency.r;
        pixels[cursor + 1] = transparency.g;
        pixels[cursor + 2] = transparency.b;
        pixels[cursor + 3] = transparency.a;
      }
    }

    canvasContext.putImageData(imageData, 0, 0);
  },
};
  </script>
</body>
</html>

Leave a Reply