One of my users recently complained (rightly so) that my limit on photo sizes of 2MB meant they had to re-size every photo before uploading them because almost no modern cameras create photo files that small. So he requested that I re-size them on the fly the way our cell phones do when we send photos via text.
I really only wanted to re-size photos larger than 2MB and leave smaller photos alone. This turned out to be pretty straightforward – the only part that took some experimentation was how to leave the smaller photos alone. It turns out that if you just return an empty string for the style, paperclip will leave the original alone. Here’s the code.
class TroopPhoto < ActiveRecord::Base
belongs_to :troop
belongs_to :photo_album
has_attached_file :photo,
:styles => {
riginal => Proc.new { |instance| instance.resize }, #stupid emoticon. That is colon original!
:large => "800x800#",
:medium => "240x160#",
:small => "100x100#"
},
:storage => :s3,
:s3_credentials => "#{Rails.root}/config/s3.yml"
attr_protected :photo_file_name, :photo_content_type, :photo_file_size, :troop_id, :photo_album_id
validates_attachment_presence :photo
validates_attachment_size :photo, :less_than => 5.megabytes, :message => "Photo size exceeds size limitation of 5MB"
def resize
if self.photo_file_size > 2000000
"2400x2400#"
else
""
end
end
end
Someone is probably going to point out that 2400 x 2400 is quite a bit smaller than 2MB and I could probably resize anything larger than 1MB to 2400 x 2400 without causing problems.
My response is … yup. I’m gonna play with it a bit to see what the best cutoff size is. But this works for now.




2 responses so far ↓
1 David Baldwin // Jul 9, 2012 at 8:43 pm
You might also consider using the “>” operator rather than “#”. This will allow you to maintain an “original” of each image with the original aspect ratio. Additionally, this might let you skip the Proc altogether, as it should not upscale images less than 2400 x 2400 and you’re already assuming that this size limit will get you under that 2mb magic number.
2 David Christiansen // Jul 10, 2012 at 7:40 am
Good call – in this situation you are exactly correct. I don’t need the proc. I’ve changed the code in TroopTrack as you suggest but I’m going to leave this post as is for two reasons:
1) Other people might not realize that ImageMagick doesn’t upscale pictures
2) The proc thing is useful in other situations, like if a user can set their own picture sizes in a model or settings or something
Thanks David!
Leave a Comment