Rails Api Save MiniMagick Image to Active Storage

1.3k views Asked by At

I'm using MiniMagick to resize my image. My method looks something like that:

def resize
    mini_img = MiniMagick::Image.new(img.tempfile.path)
    mini_img.combine_options do |c|
      c.resize '50x50^'
      c.gravity 'center'
      c.extent '50x50'
    end

    mini_img
end

Resize works, but the problem is when I try save mini_img to Active Storage, because I get error Could not find or build blob: expected attachable, got #<MiniMagick::Image. Can I somehow convert MiniMagick::Image (mini_img) to normal image and save it into Active Storage?

2

There are 2 answers

4
David Metta On BEST ANSWER

Yes, you can. Currently you are trying to save an instance of MiniMagick::Image to ActiveStorage, and that's why you receive that error. Instead you should attach the :io directly to ActiveStorage.

Using your example, if you wanted to attach mini_img to a hypothetical User, that's how you would do it:

User.first.attach io: StringIO.open(mini_img.to_blob), filename: "filename.extension"

In this example I am calling to_blob on mini_img, which is an instance of MiniMagick::Image, and passing it as argument to StringIO#open. Make sure to include the :filename option when attaching to ActiveStorage this way.

EXTRA

Since you already have the content_type when using MiniMagick you might want to provide it to ActiveStorage directly.

metadata = mini_img.data
User.first.attach io: StringIO.open(mini_img.to_blob), filename: metadata["baseName"], content_type: metadata["mimeType"], identify: false
0
N0ne On

For someone who will have a similar problem. I just changed method to:

def resize
MiniMagick::Image.new(img.tempfile.path).combine_options do |c|
    c.resize '50x50^'
    c.gravity 'center'
    c.extent '50x50'
  end

  img
end

In this solution, MiniMagick only resized the photo and did nothing else with it, so I didn't have to convert it again.