Class: RainbowColors::ImagePalette

Inherits:
Object
  • Object
show all
Defined in:
lib/rainbow_colors/image_palette.rb

Instance Method Summary collapse

Constructor Details

#initialize(image_path) ⇒ ImagePalette

Returns a new instance of ImagePalette.



3
4
5
# File 'lib/rainbow_colors/image_palette.rb', line 3

def initialize(image_path)
  @image = Magick::ImageList.new(image_path).quantize(2048, Magick::RGBColorspace)
end

Instance Method Details

#color_accentObject



56
57
58
# File 'lib/rainbow_colors/image_palette.rb', line 56

def color_accent
  RainbowColors::Palette.color_accent scheme, color_background
end

#color_backgroundObject



47
48
49
50
# File 'lib/rainbow_colors/image_palette.rb', line 47

def color_background
  # Pick the most-used color in the image
  RainbowColors::Convertor.hex_from_rgb image_colors.first
end

#color_textObject



52
53
54
# File 'lib/rainbow_colors/image_palette.rb', line 52

def color_text
  RainbowColors::Palette.color_text color_background
end

#schemeObject



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/rainbow_colors/image_palette.rb', line 7

def scheme
  colors = image_colors
  colors.map! { |rgb| RainbowColors::Convertor.hsl_from_rgb(rgb) }
  
  # Round off HSL values to nearest 10. We don't need to worry about precision
  colors.map! { |color_hsl| color_hsl.each { |key, value| color_hsl[key] = value.round(-1).to_f } }
  
  # Remove colors that are too dark or too light
  colors = colors.delete_if { |color_hsl| color_hsl[:saturation] <= 20 || color_hsl[:luminance] <= 20 || color_hsl[:luminance] >= 70 }
  
  average_colors = []
  # Get average color from hue ranges
  # 12 * 30 = 360, i.e. all possible hues
  12.times do |i|
    next if i == 0
    
    hue_floor = (i - 1) * 30
    hue_ceil  = i * 30
    colors_for_range = colors.select { |color_hsl| color_hsl[:hue] >= hue_floor && color_hsl[:hue] < hue_ceil }
    
    unless colors_for_range.empty?
      hue_sum = saturation_sum = luminance_sum = 0
      
      colors_for_range.each do |color_hsl|
        hue_sum = hue_sum + color_hsl[:hue]
        saturation_sum = saturation_sum + color_hsl[:saturation]
        luminance_sum  = luminance_sum  + color_hsl[:luminance]
      end
      
      hue = hue_sum / colors_for_range.count
      saturation = saturation_sum / colors_for_range.count
      luminance  = luminance_sum  / colors_for_range.count
      
      average_colors << { hue: hue.to_f, saturation: saturation.to_f, luminance: luminance.to_f }
    end
  end
  
  average_colors.map! { |color_hsl| RainbowColors::Convertor.hex_from_hsl color_hsl }
end