Josh Rieken
Josh Rieken

Reputation: 2266

RMagick - convert file to another format without saving to disk

I'm trying to convert a file to a specific format so I can to_blob it. I know the technique of saving to disk and specifying the extension to convert it to another format, like this:

img.write("another_filename.jpg")

I'd like to not have to touch the disk during the conversion.

Is there another way?

Upvotes: 5

Views: 2334

Answers (1)

mu is too short
mu is too short

Reputation: 434635

You can specify the format when calling to_blob. From the fine manual:

to_blob img.to_blob [ { optional arguments } ]-> string

[...]
No required arguments, however you can specify the image format (such as JPEG, PNG, etc.) and depth by calling the format and depth attributes, as well as other Image::Info attributes as appropriate, in a block associated with the method.

So you can say things like this:

png_bytes = img.to_blob { |attrs| attrs.format = 'PNG' }

Yes, the interface to to_blob is a bit odd but the strange interface is just part of the fun of working with ImageMagick.

You can also use the format= method before calling to_blob:

img.format = 'PNG'
png_bytes  = img.to_blob

Upvotes: 7

Related Questions