Last active
March 3, 2017 06:04
-
-
Save Fardinak/fa4e959ec53555a8e476 to your computer and use it in GitHub Desktop.
Extract the dominant web-safe color from a decoded image
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package dominantcolor | |
// Optionally use this importable repository instead: | |
// https://github.com/Fardinak/dominantcolor | |
import ( | |
"github.com/nfnt/resize" | |
"image" | |
"image/color" | |
"image/color/palette" | |
) | |
// Color Code Extractor | |
func extractColorCode(img image.Image) color.Color { | |
// Resize the image for faster computation | |
img = resize.Resize(100, 0, img, resize.Bilinear) | |
bounds := img.Bounds() | |
colorCount := make([]int, len(palette.WebSafe)) | |
biggest := []int{0, 0} | |
for i := 0; i <= bounds.Max.X; i++ { | |
for j := 0; j <= bounds.Max.Y; j++ { | |
pixel := img.At(i, j) | |
c := color.Palette(palette.WebSafe).Index(pixel) | |
colorCount[c]++ | |
// Find the most used color | |
if colorCount[c] > biggest[1] { | |
biggest[0] = c | |
biggest[1] = colorCount[c] | |
} | |
} | |
} | |
return palette.WebSafe[biggest[0]] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment