3

In my Rails app I have a module that takes several images, and using RMagick "stitches" them together into a new single image. I'm able to successfully create the final image, but I'm having trouble saving this new image as an attachment to a model (using CarrierWave). The method that does the stitching looks like this:

def generate_collage(params)
    final_image = ImageList.new

    # ... code that puts together the composite image ...

    return final_image.append(true).to_blob { |attrs| attrs.format = 'JPEG' }
end

I've got my User model with an uploader mounted:

class User < ActiveRecord::Base
    mount_uploader :image, UserImageUploader
end

In the CarrierWave documentation under the ActiveRecord section, they show how to assign a new image, but they assume the file already exists somewhere. In my case it doesn't yet exist on the filesystem, and I'm outputting a blob... is there any way to go from that blob to generating an image upload for CarrierWave?

I suppose I'm trying to avoid saving this image temporarily into "#{Rails.root}/tmp/" and then reading it from there... it seems like I could cut out this step and send directly to CarrierWave somehow, but I don't know how! Is it possible?

DelPiero
  • 489
  • 1
  • 10
  • 21

1 Answers1

2

I'm working on something similar right now. This should be possible, but an easy workaround is to save it to a temp file:

temp_file = Tempfile.new([ 'temp', '.png' ])

image.write(temp_file.path)

user = User.new
user.avatar = temp_file
user.save

temp_file.close
temp_file.unlink

I'm hoping to try to improve it to remove the file system dependency completely, by following the advice in one of these answers: How to handle a file_as_string (generated by Prawn) so that it is accepted by Carrierwave?

Community
  • 1
  • 1
Gal
  • 5,537
  • 1
  • 22
  • 20