e5a534c54939986a2d45c1b826a989425063ff01
[selectricity] / vendor / plugins / attachment_fu / lib / technoweenie / attachment_fu / processors / mini_magick_processor.rb
1 require 'mini_magick'
2 module Technoweenie # :nodoc:
3   module AttachmentFu # :nodoc:
4     module Processors
5       module MiniMagickProcessor
6         def self.included(base)
7           base.send :extend, ClassMethods
8           base.alias_method_chain :process_attachment, :processing
9         end
10         
11         module ClassMethods
12           # Yields a block containing an MiniMagick Image for the given binary data.
13           def with_image(file, &block)
14             begin
15               binary_data = file.is_a?(MiniMagick::Image) ? file : MiniMagick::Image.from_file(file) unless !Object.const_defined?(:MiniMagick)
16             rescue
17               # Log the failure to load the image.
18               logger.debug("Exception working with image: #{$!}")
19               binary_data = nil
20             end
21             block.call binary_data if block && binary_data
22           ensure
23             !binary_data.nil?
24           end
25         end
26
27       protected
28         def process_attachment_with_processing
29           return unless process_attachment_without_processing
30           with_image do |img|
31             resize_image_or_thumbnail! img
32             self.width  = img[:width] if respond_to?(:width)
33             self.height = img[:height]  if respond_to?(:height)
34             callback_with_args :after_resize, img
35           end if image?
36         end
37
38         # Performs the actual resizing operation for a thumbnail
39         def resize_image(img, size)
40           size = size.first if size.is_a?(Array) && size.length == 1
41           if size.is_a?(Fixnum) || (size.is_a?(Array) && size.first.is_a?(Fixnum))
42             if size.is_a?(Fixnum)
43               size = [size, size]
44               img.resize(size.join('x'))
45             else
46               img.resize(size.join('x') + '!')
47             end
48           else
49             img.resize(size.to_s)
50           end
51           self.temp_path = img
52         end
53       end
54     end
55   end
56 end

Benjamin Mako Hill || Want to submit a patch?