Charlie Prezzano
Charlie Prezzano

Reputation: 236

How to create an image in memory with the MiniMagick::Tool::Convert

I have a function that opens an image, resizes it, then sets the max # of colors to be included in its palette. This modified image is then used for internal processing. My preference is to avoid saving the image to disk, which is then immediately opened.

Is there a way to use MiniMagick::Tool::Convert and capture the output in memory?

def create_image_for_processing(image_path, resize, colors)
    MiniMagick::Tool::Convert.new do |convert|
        convert << image_path
        convert << '-resize' << resize
        convert << '-colors' << colors
        convert << 'temp.png'
    end
    MiniMagick::Image.open('temp.png')
end

Upvotes: 3

Views: 1424

Answers (2)

VAD
VAD

Reputation: 2401

Charlie Prezzano's answer looks like it should work in general but it didn't work for me so I'm going to post an alternative here. This is what did work for me:

image_data =
    MiniMagick::Tool::Convert.new do |convert|
      convert << image_path
      convert << '-resize' << resize
      convert << '-colors' << colors
      convert << 'png:-'
    end
MiniMagick::Image.read(image_data)

Upvotes: 1

Charlie Prezzano
Charlie Prezzano

Reputation: 236

This works :)

image_data =
    MiniMagick::Tool::Convert.new do |convert|
      convert << image_path
      convert << '-resize' << resize
      convert << '-colors' << colors
      convert.stdout
    end
MiniMagick::Image.read(image_data)

Upvotes: 0

Related Questions