13

I want to define a function that "call" imagemagick to convert an image.

def convert(filein,fileout):
#imagemagick>convert filein fileout

How can I call and use imagemagick with Python?

I'm running on a linux system, imagemagick is installed, and I'm not using PIL.module because it doesn't handle PPM[p3].

Michael Currie
  • 13,721
  • 9
  • 42
  • 58
Alpagut
  • 1,173
  • 5
  • 15
  • 21

4 Answers4

16

Disclaimer: I am the author of Wand.

You can easily do that using Wand, a simple binding of ImageMagick for Python. For example, the following code converts a PNG image to a JPEG image:

from wand.image import Image

with Image(filename='in.png') as img:
    img.format = 'jpeg'
    img.save(filename='out.jpg')

See this tutorial as well.

minhee
  • 5,688
  • 5
  • 43
  • 81
8

Either use one of the shell interfaces of Python (os.system, subprocess.Popen) to call the imagemagick binary, or try out PythonMagick.

Creshal
  • 493
  • 1
  • 4
  • 15
6

I would suggest u use subprocess it is safer

import subprocess
params = ['convert', 'src_file', 'result_file']
subprocess.check_call(params)
Rakesh
  • 81,458
  • 17
  • 76
  • 113
3

I have not used image magic but you could use os.system to call a shell command:

import os
os.system('imagemagick-converting-command filein fileout')   

I suggest you go with PythonMagic as Creshal said. It is provided by ImageMagic and thus must be one of the best port available for python.

crodjer
  • 13,384
  • 9
  • 38
  • 52