Segmentation Fault Django ImageMagick

214 Views Asked by At

im doing a web aplication using the API of instagram. One of the points required for this exercise is "Use a C library in a python code" so im using CTYPES to adapt ImageMagick to apply a filter to photos.

So, i've got the URL image and i want to apply the filter:

from ctypes import * 
    factor = 2
    libwand=CDLL("libMagick++.so.5")
    libwand.MagickWandGenesis()
    magick_wand = libwand.NewMagickWand()
    #url_image is a simple url like http://www.images.com/123.jpg
    libwand.MagickReadImage(magick_wand,url_image)
    libwand.MagickBlueShiftImage(magick_wand,factor);
    libwand.MagickWriteImage(magick_wand,'./login/static/images/imagenNueva.jpg');

If i do this in a simple tets.py it works fine, but once i put it in the views.py of django it produce a segmentation fault.

Here is the gdb output:

Program received signal SIGSEGV, Segmentation fault. 0x00007ffff782dfb7 in kill () at ../sysdeps/unix/syscall-template.S:81 81 ../sysdeps/unix/syscall-template.S: File or directory does not exist.

1

There are 1 best solutions below

2
On

Ensure the correct library is loaded with ctypes.CDLL. For the commands your executing, I believe you want libwand=CDLL("libMagickWand.so"). Best way to discover the correct library name is to use the MagickWand-config utility to locate the correct library name on system.

Also, for each ctypes method call, you need to specify the function signature

# Tell ctypes that the return value is a pointer
libwand.NewMagickWand.restype = c_void_p
libwand.MagickReadImage.argtypes = [c_void_p,      # MagickWand *
                                    c_char_p]      # char *
libwand.MagickBlueShiftImage.argtypes = [c_void_p, # MagickWand *
                                         c_double] # double

Without mapping C-API to python, faults will result as python will assume everything is a integer.

And of course, error/exception handling

magick_wand = libwand.NewMagickWand()
if magick_wand is None:
    raise MyException("Couldn't allocate memory")
ok = libwand.MagickReadImage(magick_wand,url_image)
if not ok:
    raise MyException("Couldn't read image")