Search code examples
ruby-on-railsattachment-fu

Flickr style resizing with attachment_fu


I want attachment_fu to resize my thumbnails in a similar way to how flickr, facebook and twitter handle this: If I want a 100x100 thumbnail I want the thumbnail to be exactly 100x100 with any excess cropped off so that the aspect ratio is preserved.

Any ideas?


Solution

  • My solution was to delve into the attachment_fu plugin folder (vendor/plugins) and edit the rmagick_processor.rb file. First I renamed resize_image to resize_image_internal, then added:

      def resize_image(img, size)  
        # resize_image take size in a number of formats, we just want  
        # Strings in the form of "square: WxH"  
        if (size.is_a?(String) && size =~ /^square: (\d*)x(\d*)/i) ||  
            (size.is_a?(Array) && size.first.is_a?(String) &&  
              size.first =~ /^square: (\d*)x(\d*)/i)  
            iw, ih = img.columns, img.rows
            aspect = iw.to_f / ih.to_f
            if aspect > 1
                shave_off = (iw - ih) / 2
                img.shave!(shave_off, 0)
            else
                shave_off = (ih-iw) / 2
                img.shave!(0, shave_off)
            end
            resize_image_internal(img, "#{$1}x#{$2}!")
        else  
          resize_image_internal(img, size) # Otherwise let attachment_fu handle it  
        end  
      end
    

    I can now use 'square: 100x100' as my geometry string. Note that the above code assumes the required output is square.