Friday, March 11, 2011

How to resize pics stored in different -2 folder through ImageMagick from Ruby on Rails application

In one of the Ruby on Rails application, I am using attachment_fu plugin, asset model used as polymorphic to upload image from various model and ImageMagick.

When the application went into production, we were uploading images and resizing to 2 different sizes, later on we found that one more size is required which will be used in the application to display the image. Now big issue was, how to resize all the uploaded image in a specific desired size in production.

One way was to download all the assets folder and then one by one resize them and rename them accordingly and then place them in their respective folder. But that was not good way as lots of effort, time and risk was involved in that.

After thinking on all the possible ways, we decided to make one method in model which will pick the collection of all the images one by one, resize them and then restore in the destination folder. This was certainly one of the most effective way of doing it. But this method will not be required again and again, so why not to have a rake task that will work instead of a method in the model.

So, at last, after lots of deep thinking, we decided to go with the rake task option which will pick images one by one, resize them and will save them in their respective folder with desired name.

Here is the code snippets to do that:

desc "Create missing featured image"
    task :create_featured_image => :environment do
      clips = Clip.all.collect
      clips.each do |fi|
        if !fi.blank? && !fi.asset.blank? && !fi.asset.public_filename(:featured).blank?
          original_image = RAILS_ROOT +  "/public/" + "#{fi.asset.public_filename}"

          destination_image = RAILS_ROOT + "/public/" + "#{fi.asset.public_filename(:featured)}"

          if !FileTest.exists?(destination_image)
            p "converting image #{}"
            system("convert  #{original_image}   -resize 250x155! #{destination_image}")

In the above code, we have taken the collection of clips, iterating over that collection, picking clip object one by one, checking if the original image exists, if yes then it will check if new image that needs to be created is already present, if no then it will create that new image, else it will not create. While execution it will show on the console which image it is resizing.

No comments:

Post a Comment