Skip to content

Instantly share code, notes, and snippets.

@kany
Created Sep 24, 2014
Embed
What would you like to do?
Cropping images with paperclip
# lib/paperclip_processors/cropper.rb
module Paperclip
class Cropper < Thumbnail
def transformation_command
if crop_command
puts "CROP: #{crop_command + super.join(' ').sub(/ -crop \S+/, '').split(' ')}"
crop_command + super.join(' ').sub(/ -crop \S+/, '').split(' ')
else
super
end
end
def crop_command
target = @attachment.instance
if target.cropping?
["-crop", "#{target.crop_width}x#{target.crop_height}+#{target.crop_x}+#{target.crop_y}"]
end
end
end
end
# Model with has_attached_file
# Logo managed by the Paperclip plugin
# http://tim-stanley.com/post/standard-web-digital-image-sizes/
has_attached_file :photo,
:styles => {
:medium => "240x160>",
:small => "100x100>",
:thumb => {:geometry => "50x50>", :processors => [:cropper]}
}
validates_attachment_content_type :photo,
:content_type => ["image/png", "image/gif", "image/jpg", "image/jpeg", "image/bmp", "image/tiff"],
:message => "Acceptable image file formats are .png, .bmp, .tiff, .jpg and .gif"
validates_attachment_size :photo, :in => 1..2.megabytes,
:message => "Please choose a smaller image. Maximum file size is 2 MB"
after_create :reprocess_photo, :if => :cropping?
def cropping?
!self.crop_x.blank? && !self.crop_y.blank? && !self.crop_width.blank? && !self.crop_height.blank?
end
private
def reprocess_photo
photo.reprocess!
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment