RMagick write fails / to_blob works

I am trying to use @img.write(path) but it’s not working (zero bytes
written). Using “to_blob” works.

 f = Tempfile.new('tmp_img')

FAILING CODE:
@img.write(f.path)

WORKING CODE:
File.open(f.path, ‘wb’) do |f|
f.syswrite(@img.to_blob)
end

Any idea ?

(RMagick 2.5.2)

Thanks for any reply.

Gaspard

Gaspard B. wrote:

I am trying to use @img.write(path) but it’s not working (zero bytes
written). Using “to_blob” works.

 f = Tempfile.new('tmp_img')

FAILING CODE:
@img.write(f.path)

WORKING CODE:
File.open(f.path, ‘wb’) do |f|
f.syswrite(@img.to_blob)
end

Image#write doesn’t know what to do with a Tempfile object. It can only
accept a string or a File object that’s been opened for output.

Image#write calls directly into ImageMagick, and ImageMagick doesn’t
know anything about Ruby objects like Tempfiles.

Image#write’s argument is in fact a String (f.path), not the Tempfile
object itself…

Gaspard B. wrote:

@img.write(f.path)

know anything about Ruby objects like Tempfiles.

Posted via http://www.ruby-forum.com/.

It’s possibly due to the file already being opened for writing. Try
f.close first, then @img.write(f.path).

Gaspard B. wrote:

Image#write’s argument is in fact a String (f.path), not the Tempfile
object itself…

I see. I overlooked that earlier.

Normally Image#write either succeeds or raises an exception. I have
never seen it silently fail.

If you like, open a support request track on RubyForge with a simple
reproduction (just Ruby and RMagick, no Rails, etc.) and let me know
what O/S you’re on and what version of ImageMagick you have installed.
I’ll be glad to investigate.

Serabe wrote:

and it works. Maybe RMagick just needs to check if there is an
extension ImageMagick can use.

Cheers,

Serabe

Duh. I had to figure this out just a few weeks ago. I should’ve
remembered. I must be getting old.

The Tempfile path ends in .0, which is not an extension ImageMagick can
use. As Serabe so intelligently points out, adding a valid extension
works. You can also add a prefix: “jpeg:” + f.path.

Thanks for being smarter than me, Serabe!

Hi, Gaspard and Tim:

I’ve tried changing:

@img.write(f.path)

to

@img.write(f.path+’.jpg’)

and it works. Maybe RMagick just needs to check if there is an
extension ImageMagick can use.

Cheers,

Serabe

You guys rock !

Thanks very much. Adding ‘jpeg:’ prefix solved the problem. This
solution is better because it keeps the temporary filename so the file
is still cleaned up.

Solution:

 tmp_path = Tempfile.new('tmp_img').path
 @img.write('jpeg:' + tmp_path)   # writes to tmp_path

Thanks !

Gaspard

Le 26 août 08 à 00:47, Tim H. a écrit :

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs