Last active
December 14, 2021 12:52
-
-
Save skyporter/6fc4c35e1ce2d1f6048f876d73f7e34c to your computer and use it in GitHub Desktop.
return dominant color on a picture with minimagick
This file contains 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
class ImageColorInfo | |
def initialize(image) | |
@image = image | |
end | |
def dominant_color | |
dominant_colors.first | |
end | |
def dominant_colors | |
histogram.sort_by(&:first).reverse.map(&:last) | |
end | |
def histogram | |
@histogram ||= histogram_result.split("\n").map do |data| | |
count, color = data.split(":", 2) | |
[ | |
count.to_i, | |
color.strip.split(" ")[1][0, 7] | |
] | |
end | |
end | |
private | |
# returned format example: | |
# " 4290: (2.59281,2.51622,2.50009) #030303 srgb(1.01679%,0.986752%,0.980429%)\n 104: (3.90722,2.76358,2.89232) #040303 srgb(1.53224%,1.08376%,1.13424%)\n 215: (89.8296,20.9757,19.2815) #5A1513 srgb(35.2273%,8.22577%,7.56136%)\n 391: (173.48,38.3166,28.8013) #AD261D srgb(68.0313%,15.0261%,11.2946%)" | |
def histogram_result | |
temp_file = Tempfile.new | |
temp_file.binmode | |
temp_file.write @image.download | |
begin | |
convert = MiniMagick::Tool::Convert.new | |
convert << temp_file.path | |
convert.resize("100x100") | |
convert << '-format' << '%c' | |
convert << '-colors' << '6' | |
convert << 'histogram:info:-' | |
convert.call | |
rescue MiniMagick::Error | |
"" | |
ensure | |
temp_file.unlink | |
end | |
end | |
end |
This file contains 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
class MyModel | |
before_save :track_if_image_changed | |
after_save_commit :save_background_color, prepend: true | |
private | |
def save_background_color | |
return unless image_changed? | |
return unless image.attached? | |
return unless (color = ImageColorInfo.new(image).dominant_color) | |
update_columns background_color: color | |
end | |
def track_if_image_changed | |
@track_if_image_changed = attachment_changes.any? | |
end | |
def image_changed? | |
@track_if_image_changed == true | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment