Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
RandomDude560 opened this issue Jul 31, 2023 · 1 comment

Comments

@RandomDude560
Copy link

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
Copy link

prjctimg commented Aug 8, 2023

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants