Veerasundaravel's Ruby on Rails Weblog

April 28, 2010

Image processing using Rmagick and S3 upload

require “rubygems”
require ‘RMagick’
require ‘aws/s3’
include AWS::S3

#Download the image from an external site.
status, image_data = Net::HTTP.get_response(URI.parse(‘http://www.example.com/testing-image.jpg’))
raise “Not able to download the photo” if status.code != “200” || image_data.empty?
#Now create a new ImageList object
orig_img = Magick::ImageList.new
#And use the downloaded image content using the method from_blob
orig_img.from_blob(image_data)
#Resizing the image to a fixed dimension.
thumb = orig_img.resize_to_fill(120, 90)
file_extension = property.photo.split(“.”).last
temp_file_name = “photo_image.#{file_extension}”
#Now write the to a temparary file
thumb.write(temp_file_name)
#Connect to S3 server using the available login_credentials
s3_connection = AWS::S3::Base.establish_connection!(:access_key_id =>s3_access_key_id,:secret_access_key => s3_secret_access_key)
#Store the temparary file in s3 bucket
S3Object.store(file_name, open(temp_file_name ), s3_bucket_name, :access => :public_read)
#Remove the temparary file
FileUtils.rm temp_file_name