zhanziyang / vue-croppa

A simple straightforward customizable mobile-friendly image cropper for Vue 2.0.
https://zhanziyang.github.io/vue-croppa/
ISC License
967 stars 128 forks source link

Concept: Extract most frequently used color #228

Open topada opened 4 years ago

topada commented 4 years ago

Hi there, I have been working on an extension that analyses eight samples along the edge of the canvas and extracts the most frequently used color, excluding white. I am trying to extend uploaded brand logos in case they have a colored background and cannot be scaled.

Maybe this concept could spark a new feature idea for the vue-croppa plugin?

Cheers, Jonas

sample-spots


methods: {
    onDraw: function(ctx) {
      //https://bit.ly/2Zf1lth

      //get canvas dimensions
      let { width, height } = ctx.canvas;

      //define sample spots
      let sampleSpots = [
        [0, 0],
        [width * 0.5, 0],
        [width - 1, 0],
        [width - 1, height * 0.5],
        [width - 1, height - 1],
        [width * 0.5, height - 1],
        [0, height - 1],
        [0, height * 0.5]
      ];

      //get samples
      let samples = [];
      let samplesHex = [];
      for (let i = 0; i < sampleSpots.length; i++) {
        //console.log("sample:", i, sampleSpots[i][0]);

        let px = ctx.getImageData(
          sampleSpots[i][0], //x
          sampleSpots[i][1], //y
          1, //w
          1 //h
        ).data;

        samples[i] = px;
        samplesHex[i] =
          "#" + ("000000" + this.rgbToHex(px[0], px[1], px[2])).slice(-6);
      }

      // console.log("sH:", samplesHex);
      // console.log("mode:", this.mode(samplesHex));

      //filter White samples from Array
      let samplesHexColor = samplesHex.filter(e => e !== "#ffffff");

      // console.log("sHColor:", samplesHexColor);
      // console.log("mode:", this.mode(samplesHexColor));

      this.canvasColor = this.mode(samplesHexColor);
    },
    //https://bit.ly/2Zf1lth
    rgbToHex: function(r, g, b) {
      if (r > 255 || g > 255 || b > 255) throw "Invalid color component";
      return ((r << 16) | (g << 8) | b).toString(16);
    },
    //https://bit.ly/2WwF2NK
    mode: function(arr) {
      return arr
        .sort(
          (a, b) =>
            arr.filter(v => v === a).length - arr.filter(v => v === b).length
        )
        .pop();
    }
}`
micardona96 commented 4 years ago

I like it