Create paperclip attachment from rmagick image
Asked Answered
J

3

9

I have a problem to find a way to save an image created with RMagick in a paperclip attachment.

imageList = Magick::ImageList.new
imageList.new("images/apple.gif", "images/overlay.png")
...
picture = imageList.flatten_images

I am in a model that have an attached file

has_attached_file :picture, :url => ..., :path => ...

and i just want my image returned by imageList.flatten_images to be saved as the picture of my model.

Does anyone know how to do it easily please?

thanks

Jawbreaker answered 27/10, 2010 at 16:2 Comment(0)
P
12

Let's see if that's what you need

picture = imageList.flatten_images
file = Tempfile.new('my_picture.jpg')
picture.write(file.path)
YourModel.create(:picture => file, ...)

Change YourModel with the model you are using...

Proximate answered 27/10, 2010 at 19:18 Comment(1)
I had to change the my_picture to end with .jpg for the processing to work. Thanks!Piccolo
S
5

You should force the extension on TempFile.new; in this case I pull the original image from S3 or some such, this is happening in the model of course:

orig_img = Magick::ImageList.new(self.photo.url(:original))

#process image here

# Force extension with array form:
file = Tempfile.new(['processed','.jpg'])
orig_img.write(file.path)
self.photo = file
self.save
Shockey answered 29/4, 2013 at 22:52 Comment(0)
M
0

In the later versions of Paperclip (mine is 5.0.0), you'll need to provide Paperclip's own Tempfile instance:

file = Paperclip::Tempfile.new(["processed", ".jpg"])
thumb.write(file.path)
result = YourModel.create(image: file)

This preserves the file extension at the end of the filename, so that it is recognized by Paperclip when it's uploaded.

Mychal answered 31/1, 2017 at 17:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.