daveliu (owner)

Revisions

gist: 6795 Download_button fork
public
Public Clone URL: git://gist.github.com/6795.git
Embed All Files: show embed
crop_with_paperclip.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
   def crop!( options = {} )
        # setup the default params
        options[:crop_left] ||= 0
        options[:crop_top] ||= 0
        options[:crop_width] ||= 100
        options[:crop_height] ||= 100
        # passed params could be strings, so convert them to ints/booleans
        crop_l = options[:crop_left].to_i
        crop_t = options[:crop_top].to_i
        crop_w = options[:crop_width].to_i
        crop_h = options[:crop_height].to_i
 
        # call the appropriate crop method for the image processor we're using with attachment_fu
         crop_with_paperclip! crop_l, crop_t, crop_w, crop_h
  end
 
  def crop_with_paperclip!(crop_l, crop_t, crop_w, crop_h)
        dst = Tempfile.new("stream")
        dst.binmode
        src = File.join(RAILS_ROOT, "public/#{self.photo.url(:large)}")
        command = <<-end_command
#{ Paperclip.path_for_command('convert') }
"#{src}"
-crop "#{crop_w}x#{crop_h}+#{crop_l}+#{crop_t}"
"#{File.expand_path(dst.path)}"
end_command
        
        success = system(command.gsub(/\s+/, " "))
 
        if success && $?.exitstatus != 0
          raise PaperclipError, "There was an error processing this thumbnail"
        end
 
        thumb = Paperclip::Thumbnail.make(dst, "48x48#", nil, true)
 
        thumb_path = File.join(RAILS_ROOT, "public/#{self.photo.url(:thumb)}")
        begin
          FileUtils.rm(thumb_path) if File.exist?(thumb_path)
        rescue Errno::ENOENT => e
          # ignore file-not-found, let everything else pass
        end
 
        result = thumb.stream_to(thumb_path)
        thumb.close
        result.close
   end