zygisS22 / color-palette-extraction

Create a color palette using median cut with Javascript
MIT License
106 stars 32 forks source link

Don't process the full resolution image, instead scale it down first. #3

Open RandomDude560 opened 1 year ago

RandomDude560 commented 1 year ago

This improves processing speed and the result shouldn't be too far off.

const main = () => {
  const imgFile = document.getElementById("imgfile");
  const image = new Image();
  const file = imgFile.files[0];
  const fileReader = new FileReader();

  // Whenever file & image is loaded procced to extract the information from the image
  fileReader.onload = () => {
    image.onload = () => {
      // Set the canvas size to be the same as of the uploaded image
      const canvas  = document.getElementById("canvas");
      const dw      = 64;
      const dh      = 64;
      canvas.width  = dw;
      canvas.height = dh;
      const ctx = canvas.getContext("2d");
      ctx.drawImage(image, 0, 0, dw, dh);

      /**
       * getImageData returns an array full of RGBA values
       * each pixel consists of four values: the red value of the colour, the green, the blue and the alpha
       * (transparency). For array value consistency reasons,
       * the alpha is not from 0 to 1 like it is in the RGBA of CSS, but from 0 to 255.
       */
      const imageData = ctx.getImageData(0, 0, dw, dh);

      // Convert the image data to RGB values so its much simpler
      const rgbArray = buildRgb(imageData.data);

      /**
       * Color quantization
       * A process that reduces the number of colors used in an image
       * while trying to visually maintin the original image as much as possible
       */
      const quantColors = quantization(rgbArray, 0);

      // Create the HTML structure to show the color palette
      buildPalette(quantColors);
    };
    image.src = fileReader.result;
  };
  fileReader.readAsDataURL(file);
};
prjctimg commented 1 year ago

Noticed that my mobile browser (Samsung Internet) would show a page not responding dialog whenever I tried to load an image. Scaling it down would be a great way to save computing resources.