merged in changes from live version
[selectricity-live] / vendor / plugins / attachment_fu / lib / technoweenie / attachment_fu / processors / rmagick_processor.rb
1 require 'RMagick'
2 module Technoweenie # :nodoc:
3   module AttachmentFu # :nodoc:
4     module Processors
5       module RmagickProcessor
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 RMagick Image for the given binary data.
13           def with_image(file, &block)
14             begin
15               binary_data = file.is_a?(Magick::Image) ? file : Magick::Image.read(file).first unless !Object.const_defined?(:Magick)
16             rescue
17               # Log the failure to load the image.  This should match ::Magick::ImageMagickError
18               # but that would cause acts_as_attachment to require rmagick.
19               logger.debug("Exception working with image: #{$!}")
20               binary_data = nil
21             end
22             block.call binary_data if block && binary_data
23           ensure
24             !binary_data.nil?
25           end
26         end
27
28       protected
29         def process_attachment_with_processing
30           return unless process_attachment_without_processing
31           with_image do |img|
32             resize_image_or_thumbnail! img
33             self.width  = img.columns if respond_to?(:width)
34             self.height = img.rows    if respond_to?(:height)
35             callback_with_args :after_resize, img
36           end if image?
37         end
38       
39         # Performs the actual resizing operation for a thumbnail
40         def resize_image(img, size)
41           size = size.first if size.is_a?(Array) && size.length == 1 && !size.first.is_a?(Fixnum)
42           if size.is_a?(Fixnum) || (size.is_a?(Array) && size.first.is_a?(Fixnum))
43             size = [size, size] if size.is_a?(Fixnum)
44             img.thumbnail!(*size)
45           else
46             img.change_geometry(size.to_s) { |cols, rows, image| image.resize!(cols, rows) }
47           end
48           self.temp_path = write_to_temp_file(img.to_blob)
49         end
50       end
51     end
52   end
53 end

Benjamin Mako Hill || Want to submit a patch?