Extract Common Colors From An Image Using Ruby

Here’s a great snippet of Ruby script that you might find helpful, especially if you’re working on a site’s color scheme based on an image source. This code will basically take an image via a provided path or URL that directs to it, extract the seven most common colors it finds and then return their hex values.

def extract_colors(src)
 image = Magick::ImageList.new(src)
 colors = []
 q = image.quantize(7, Magick::RGBColorspace)
 palette = q.color_histogram.sort {|a, b| b[1] <=> a[1]}
 (0..6).each do |i|
 c = palette[i].to_s.split(',').map {|x| x[/\d+/]}
 c.pop
 c[0], c[1], c[2] = [/c], c[1], c[2]].map { |s| 
 s = s.to_i
 if s / 255 > 0 # not all ImageMagicks are created equal....
 s = s / 255
 end
 s = s.to_s(16)
 if s.size == 1 
 '0' + s
 else
 s
 end
 }
 colors << '#' + c.join('')
 end
 return colors
end

Incoming search terms for the article:

Related Posts

Redirecting Users To Bypass WordPress Dashboard

Twitter Feed Reader Using PHP

Add Fonts to Your Site Using Google Web Fonts

How to Create a Clean and Elegant Blog Layout

Leave a Reply









CommentLuv Enabled