ruby on rails - paperclip imagemagick convert to grayscale and crop to fit 144x144# -
client.rb
has_attached_file :avatar, :path => ":rails_root/public/system/:attachment/:id/:style/:filename", :url => "/system/:attachment/:id/:style/:filename", :styles => {:thumb => "144x144#", :grayscale => { :processors => [:grayscale] }}
the thumb version version works great, image cropped required size, grayscale converts image grayscale, image not being cropped, here grayscale generator found on stackoverflow:
lib/grayscale.rb
module paperclip # handles grayscale conversion of images uploaded. class grayscale < processor def initialize file, options = {}, attachment = nil super @format = file.extname(@file.path) @basename = file.basename(@file.path, @format) end def make src = @file dst = tempfile.new([@basename, @format]) dst.binmode begin parameters = [] parameters << ":source" parameters << "-colorspace gray" parameters << ":dest" parameters = parameters.flatten.compact.join(" ").strip.squeeze(" ") success = paperclip.run("convert", parameters, :source => "#{file.expand_path(src.path)}[0]", :dest => file.expand_path(dst.path)) rescue paperclipcommandlineerror => e raise papercliperror, "there error during grayscale conversion #{@basename}" if @whiny end dst end end end
to convert image grayscale params being sent imagemagick in array, question - params have send imagemagick "144x144#"
in paperclip.
i tried follow logs see "144x144#"
looks in logs, looking this: -crop '144x144+30+0'
, tried use in generator , send params like:
parameters = [] parameters << ":source" parameters << "-crop '144x144+30+0'" parameters << "-colorspace gray" parameters << ":dest"
and looked worked if used same image uploaded before, if upload 1 image cropped wrong. came conclusion param: -crop '144x144+30+0'
generated paperclip specific image size, , different size different params sent fit 144px.
how crop image in generator fit equivalent of 144x144#
paperclip or params need send imagemagick achieve this. thank you.
i decided go other way, i'll use cropped file has desired size , use imagemagick convert 1 grayscale , save right folder after model saved. grayscale processor can removed used system command work imagemagick.
p.s. there might downsides of answer, couldn't find any.
client.rb
has_attached_file :avatar, :path => ":rails_root/public/system/:attachment/:id/:style/:filename", :url => "/system/:attachment/:id/:style/:filename", :styles => {:thumb => "144x144#", :grayscale => "144x144#"} after_save :convert_grayscale def convert_grayscale system "convert public/system/avatars/#{self.id}/thumb/#{self.avatar.original_filename} -fx '(r+g+b)/3' public/system/avatars/#{self.id}/grayscale/#{self.avatar.original_filename}" end
result
Comments
Post a Comment