0

I'm using the tempfile module and imagemagick and when i try to run this code:

width = height = 100
temp_file = tempfile.NamedTemporaryFile()
canvas = "convert -size {}x{} canvas:black {}/canvas.png".format(scale_width, scale_height, temp_file.name)
os.system(canvas)

I get the following error:

convert: unable to open image /var/folders/jn/phqf2ygs0wlgflgfvvv0ctbw0009tb/T/tmpeMcIuh/canvas.png': Not a directory @ error/blob.c/OpenBlob/2705. convert: WriteBlob Failed /var/folders/jn/phqf2ygs0wlgflgfvvv0ctbw0009tb/T/tmpeMcIuh/canvas.png' @ error/png.c/MagickPNGErrorHandler/1630.

What could be the problem? I'm just trying to create a black image (resolution of 100x100) stored in a randomly generated temp file.

Thanks!

Gambit2007
  • 3,260
  • 13
  • 46
  • 86

1 Answers1

1

You have to leave the /canvas.png bit. The temporary file created by tempfile.NamedTemporaryFile() was /var/folders/jn/phqf2ygs0wlgflgfvvv0ctbw0009tb/T/tmpeMcIuh. So using it as parent directory for the output file raises the error by imagemagick.

To specify the output format PNG by filename extension, the temporary file can be created with the suffix keyword argument:

temp_file = tempfile.NamedTemporaryFile(suffix='.png')

Additionally, you should use the subprocess module to run subprocesses. That way you do not have to use string formatting the whole command in order to pass the subprocesses' arguments, e.g.

subprocess.check_call(['convert',
                       '-size', '{}x{}'.format(scale_width, scale_height),
                       'canvas:black',
                       temp_file.name])

And another remark: NamedTemporaryFile() opens a file descriptor, which you should close right away. The docs also state that you are in charge of deleting the file again.

code_onkel
  • 2,759
  • 1
  • 16
  • 31
  • but then how could i tell imagemagick i want a .png file named a certain way in that location? – Gambit2007 Jun 21 '16 at 19:55
  • `NamedTemporaryFile()` has a `suffix` keyword argument. Answer edited accordingly. – code_onkel Jun 21 '16 at 19:57
  • Close the file descriptor right away? Then there's the inconsistency with the `mkstemp` return value being a tuple. Doesn't the `tempfile` API seem a little wonky to be included in the standard library? – Tom Russell Dec 31 '17 at 05:21