Search code examples
ruby-on-railsimage-processingfile-iopapercliprmagick

How to create an RMagick image from a Paperclip attachment?


Suppose I've got an image stored as a paperclip attachment. I want to use this image in RMagick to compose other images. But when I ask paperclip about it, I'm handed a URL which hands back the image data; and I guess I could read this into a file, and then read the file back into RMagick -- and in fact, that's what I'm planning on doing for now -- but it seems like there very well ought to be a more direct way.

In other words, my question is the inverse of this one: how to create a Paperclip attachment from an RMagick image? I want to know the most direct means of creating an RMagick image from a Paperclip-attached picture.

UPDATE: Just in case it wasn't clear -- the basic problem is that ImageList.new() won't accept the path because paperclip hands back a URL and RMagick is apparently expecting a local filesystem path. Perhaps I'm missing something here, though. Thanks!


Solution

  • You're using Ruby. Monkey-patch Paperclip::Attachment!

    # lib/paperclip_magick.rb
    require 'RMagick'
    
    module PaperclipMagick
      def to_rmagick(style_name = default_style)
         @image_list ||= ImageList.new(self.path(style_name))
      end
    end
    
    Paperclip::Attachment.send(:include, Magick)
    Paperclip::Attachment.send(:include, PaperclipMagick)
    

    Or something along those lines.