Skip to content

Instantly share code, notes, and snippets.

@Fardinak
Last active March 3, 2017 06:04
Show Gist options
  • Save Fardinak/fa4e959ec53555a8e476 to your computer and use it in GitHub Desktop.
Save Fardinak/fa4e959ec53555a8e476 to your computer and use it in GitHub Desktop.
Extract the dominant web-safe color from a decoded image
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