Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 716
Josh Rieken Avatar asked May 29 '13 19:05

Josh Rieken


1 Answers

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
like image 76
mu is too short Avatar answered Nov 15 '22 08:11

mu is too short