Search code examples
ruby-on-railsrails-activestorage

How to save a copy of image after using variant option in ActiveStorage.


I am facing this issue with ActiveStorage where I need to process an image, my requirement is to save the processed image and attach it to a new model after crop and other transformations.


Solution

  • @George has a great answer, still I would mention mine,which should work with rails 5.2 as per my understanding of your question,

    Create a temporary file, and fetch the file first, if it is in your cloud storage, if not then you don't need this part, just get the path using blob in that case.

    path = Rails.root.join('tmp', ModelVariable.main_image.blob.filename.to_s).to_s
    File.open(path, 'wb') do |file|
      file.write(ModelVariable.main_image.blob.download)
    end
    

    Do your customization

    customize_image = MiniMagick::Image.open(path)
    customize_image.crop(crop_params)
    

    Attach it to the different model you wanted to

    file = File.open(customize_image.path)
    filename = Time.zone.now.strftime("%Y%m%d%H%M%S") + ModelVariable.main_image.blob.filename.to_s
    NewModelVaribale.customized_image.attach(io: file, filename: filename)
    

    Save it

    customized_product.save
    

    Hope this works for you :)