Return to Snippet

Revision: 54745
at January 10, 2012 11:39 by kellishaver


Updated Code
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[0], 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

Revision: 54744
at January 10, 2012 10:27 by kellishaver


Initial Code
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[0], c[1], c[2]].map { |s| 
            s = s.to_i
            if s > 255 # 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

Initial URL

                                

Initial Description
Takes an image (path or url) and extracts the 7 most common colors and returns their hex values.

Initial Title
Extract most common colors from an image

Initial Tags
images, color

Initial Language
Ruby