Search code examples
ruby-on-railsshrine

Shrine.rb - How to access the file path / raw file after it's been uploaded


I have some other tasks that can be performed on images. Like for instance selecting multiple images, and combining them into a single image. I have that part working with RMagick and local files, and I have the upload part working with Shrine, but I need to connect the two. Once an image has been uploaded (ideally the solution should work with either local filesystem storage and S3), how can I get access to the file again, to manipulate it with ImageMagick/RMagick? I assume if I'm using S3, I'll need to DL the images from S3 to the server and store them temporarily? Is there any other way of doing this?


Solution

  • You can download any uploaded file to a temporary file using Shrine::UploadedFile#download:

    tempfile = photo.image.download
    # or
    tempfile = photo.image[:original].download
    

    This returns a Tempfile instance, which is a wrapper around File, so you can access the location on disk via #path:

    system "convert #{tempfile.path} -resize 500x500 output.jpg"
    

    For image processing I would recommend the ImageProcessing gem, which automatically generates a Tempfile as the result (which is closed & deleted on garbage collection if it hasn't been previously).