Created
September 24, 2014 01:59
-
-
Save kany/8123e7c78b20716ed0e0 to your computer and use it in GitHub Desktop.
Cropping images with paperclip
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
# 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 |
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
# 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