ibezkrovnyi / image-quantization

Image Quantization Library with alpha support (based on https://github.com/leeoniya/RgbQuant.js, https://github.com/timoxley/neuquant and http://www.ece.mcmaster.ca/~xwu/cq.c)
138 stars 11 forks source link

How to put pointArray back to a canvas and how to get the percentages of colors in the palette? #81

Closed Dylan190774 closed 2 years ago

Dylan190774 commented 3 years ago

I'm trying to use this library. I succeeded in getting a palette from a canvas in n colors. I then want to apply this palette to another canvas. I use the function applyPaletteSync, which returns a pointArray, but how can I copy this to back to a canvas, so it can be displayed?

One other question is if it's possible to get an amount or percentage for each color in the palette?

Dylan190774 commented 3 years ago

Never mind, found it myself:

      let pointContainer = imageq.utils.PointContainer.fromHTMLCanvasElement(canvas);

      const outPointContainer = imageq.applyPaletteSync(pointContainer, palette, {
        colorDistanceFormula: 'euclidean', // optional
        imageQuantization: 'floyd-steinberg', // optional
      });

      let ctx = canvas.getContext("2d");
      let imgdata = ctx.createImageData(canvas.width, canvas.height);
      let imgarray = outPointContainer.toUint8Array();

      for (let i = 0; i < imgarray.length; i += 4) {
        imgdata.data[i + 0] = imgarray[i + 0];  // R value
        imgdata.data[i + 1] = imgarray[i + 1];  // G value
        imgdata.data[i + 2] = imgarray[i + 2];  // B value
        imgdata.data[i + 3] = imgarray[i + 3];  // A value
      }

      ctx.putImageData(imgdata, 0 ,0);

While iterating through all pixels of course it's also quite easy to calculate the percentage of each color.