Monday, July 14, 2008

Resize existing images when using attachment_fu

If you use the attachment_fu plugin and want to resize all your existing image files after changing any of your thumbnail formats, write a littler runner script like this:

    1 # resize_images.rb
2 only_this = ARGV[0]
3 classes = [
4 'Photo',
5 ]
6 classes = only_this.blank? ? classes : [only_this]
7 classes.each do |klass|
8 puts "resizing all #{klass.to_s.tableize}"
9 Kernel.const_get(klass).find(:all, :conditions => 'parent_id IS NULL').each do |image|
10 puts "...#{image.public_filename}"
11 temp_file = image.create_temp_file
12 image.attachment_options[:thumbnails].each { |suffix, size|
13 image.create_or_update_thumbnail(temp_file, suffix, *size)
14 }
15 end
16 end
17

which you can call with

./script/runner ./script/resize_images.rb 

if you want to resize all images stores with attachment_fu. Or if you only want to resize your Photo model images:

./script/runner ./script/resize_images.rb Photo