The image cropping and uploading is essential part of any web application now days. Recently, I was working on a web application built on ROR platform. Initially we were using attachment_fu gem for image uploading but later there were requirements of cropping the image. I looked for the option for cropping in the attachment_fu but couldn’t found any option for image cropping in it. Finally after go through documentation for attachment_fu and googling for alternative, I found a gem called ‘Paperclip’. Paperclip gem is used for image upload and cropping but no straight forward integration with attachment_fu. So, I come up with idea of integrating attachment_fu with image cropping feature and shall explain step to step implementation of image cropping using attachment_fu.
Image Crop:
There are many javascripts from hotscripts which can be used for image cropping and I have used one of the javasript “Javascript Image Cropper UI” .
Image Processing
The above javascript shall give us the dimensions for the cropped image and we need to process the image using gem ‘RMagick’
=start rdoc This method takes crop image dimensions along with the original image path and re-sized the image to the desired size x: left most x coordinate of image for cropped image from JavaScript y: left most y coordinate of image for cropped image from JavaScript Width: width of image for cropped image from JavaScript Height: height of image for cropped image from JavaScript Path: Image path from JavaScript =end def self.update_attributes_crop(x,y,width,height,path) # Get the path of the Directory where Image should be stored path = File.dirname(__FILE__) + "/../../public/#{path}" orig_img = Magick::ImageList.new(path) scale = orig_img.crop(x.to_i,y.to_i,width.to_i,height.to_i, true) crop_img = Magick::Image.new(width.to_i,height.to_i) orig_img = crop_img.composite(scale,0,0,Magick::OverCompositeOp) orig_img.write(path) end
Upload image to Amazon S3
If you want to upload the image to Amazon S3 then you can use :
S3_copy(source, destination, bucket) line of code in your controller
=start rdoc This method upload the file from local drive to Amazon S3 bucket Source: source(path) of image from rails server Destination: destination (relative path) of Image on S3 server Bucket: your S3 bucket name for image upload =end def S3_copy(source, destination, bucket) AWS::S3::Base.establish_connection!( :access_key_id => S3_access_key_id, :secret_access_key => S3_secret_access_key ) AWS::S3::S3Object.copy(source,destination,bucket,:access => :public_read) policy = AWS::S3::S3Object.acl(destination,bucket) policy.grants << AWS::S3::ACL::Grant.grant(:public_read) policy.grants << AWS::S3::ACL::Grant.grant(:public_read_acp) begin AWS::S3::S3Object.acl(destination, bucket, policy) rescue p 'Issue occurred while granting access for the file' end end
I hope using above approach you can do image cropping and uploading. Please let me know if you have any questions