Question

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?

Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top