merged in from code from the other master
[selectricity] / vendor / plugins / attachment_fu / lib / technoweenie / attachment_fu / processors / image_science_processor.rb
1 require 'image_science'
2 module Technoweenie # :nodoc:
3   module AttachmentFu # :nodoc:
4     module Processors
5       module ImageScienceProcessor
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 Image Science image for the given binary data.
13           def with_image(file, &block)
14             ::ImageScience.with_image file, &block
15           end
16         end
17
18         protected
19           def process_attachment_with_processing
20             return unless process_attachment_without_processing && image?
21             with_image do |img|
22               self.width  = img.width  if respond_to?(:width)
23               self.height = img.height if respond_to?(:height)
24               resize_image_or_thumbnail! img
25             end
26           end
27
28           # Performs the actual resizing operation for a thumbnail
29           def resize_image(img, size)
30             # create a dummy temp file to write to
31             # ImageScience doesn't handle all gifs properly, so it converts them to
32             # pngs for thumbnails.  It has something to do with trying to save gifs
33             # with a larger palette than 256 colors, which is all the gif format
34             # supports.
35             filename.sub! /gif$/, 'png'
36             content_type.sub!(/gif$/, 'png')
37             temp_paths.unshift write_to_temp_file(filename)
38             grab_dimensions = lambda do |img|
39               self.width  = img.width  if respond_to?(:width)
40               self.height = img.height if respond_to?(:height)
41               img.save self.temp_path
42               self.size = File.size(self.temp_path)
43               callback_with_args :after_resize, img
44             end
45
46             size = size.first if size.is_a?(Array) && size.length == 1
47             if size.is_a?(Fixnum) || (size.is_a?(Array) && size.first.is_a?(Fixnum))
48               if size.is_a?(Fixnum)
49                 img.thumbnail(size, &grab_dimensions)
50               else
51                 img.resize(size[0], size[1], &grab_dimensions)
52               end
53             else
54               new_size = [img.width, img.height] / size.to_s
55               img.resize(new_size[0], new_size[1], &grab_dimensions)
56             end
57           end
58       end
59     end
60   end
61 end

Benjamin Mako Hill || Want to submit a patch?