Created
May 12, 2017 22:47
-
-
Save brobertsaz/d4a9d6440b7d5aac7e86eb6c1dfd7759 to your computer and use it in GitHub Desktop.
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
require 'rmagick' | |
class GetColors | |
def initialize(image, brand, campaign=nil) | |
@image = image | |
@brand = brand | |
@campaign = campaign | |
end | |
def perform | |
colors_from_image | |
end | |
private | |
def colors_from_image | |
url = @image.gsub('https', 'http') | |
original = Magick::Image.read(url).first | |
quantized = original.quantize(6, Magick::RGBColorspace) | |
colors = sort_light_to_dark(quantized) | |
set_colors(colors) | |
end | |
def sort_light_to_dark(img) | |
histo = img.color_histogram | |
histo.sort_by { |a| -a[0].to_hsla[2] }.map { |color, count| color } | |
end | |
def set_colors(colors) | |
count = 1 | |
hex_list = [] | |
colors.each do |color| | |
hex = color.to_color(Magick::AllCompliance, false, 8, true) | |
color_attr = "color" + count.to_s | |
hex_list.push hex | |
# Update brand colors | |
@brand.send("#{color_attr}=", hex) | |
@brand.save! | |
bc = @brand.colors.create(name: "color" + count.to_s, value: hex) | |
bc.save | |
# Update campaign colors | |
if @campaign.present? | |
@campaign.send("#{color_attr}=", hex) | |
@campaign.save! | |
end | |
count += 1 | |
end | |
if @campaign.present? | |
# Loop through @campaign background widgets and update bg_colors | |
if @campaign.widgets | |
@campaign.widgets.where(type: 'BackgroundWidget').each_with_index do |widget, i| | |
if hex_list[i].present? | |
widget.bg_color = hex_list[i] | |
else | |
widget.bg_color = hex_list.sample | |
end | |
widget.save! | |
end | |
end | |
if @campaign.login_object | |
@campaign.login_object.button_color = hex_list[3] | |
@campaign.login_object.font_color = hex_list[2] | |
@campaign.login_object.save! | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment