Recreating thumbnails with attachment_fu

Posted on May 25, 2008

In one of my apps, the need arose to use a new thumbnail size (using attachment_fu). My problem was I had a ton of existing images that I would have to create this thumbnail size for. But how? A google search didn’t turn up much. So i threw together a little instance method that would make quick and short work or creating (or re-creating) a thumbnail for images i already had in my database. I just stuck it in an initializer with my other attachment_fu hacks. It goes a little something like this


module Technoweenie 
  module AttachmentFu
    module InstanceMethods
      def create_thumbnail_size(target_size)
        actual_size = self.attachment_options[:thumbnails][target_size]
        raise "this class doesn't have a thubnail size for #{target_size}" if actual_size.nil?
        tmp = self.create_temp_file
        self.create_or_update_thumbnail(tmp, target_size.to_s, actual_size)
        FileUtils.rm_rf(Dir.glob(File.join(RAILS_ROOT, 'tmp', 'attachment_fu', '*')))
      end
    end
  end
end

nothing fancy and by no means the “best it could be” but meh, it gets the job done for me. Here an example of usage:

Say you have an Avatar class that you stuck your “has_attachment” on and you’ve decided you want to generate thumbnails of a new size. You designate this new size as “smaller” (in your has_attachment options, you’ve added it like so, :thumbnails => {:thumb => ‘75×75>’, :smaller => ‘25×25>‘}). To create “smaller” avatar thumbnails, you’d grab all the avatars that need one and call create_thumbnail_size on each one. Like so…
avatar. create_thumbnail_size(:smaller)

Voila. Thumbnails are recreated and you can move on. cheers!

Comments
  1. IvorAugust 15, 2008 @ 02:48 PM

    Hi. Thanks a lot for this! It saved me hours of time. I had the previlege of googling and finding this. Many thanks!

Post a comment
Comment