Search code examples
imagemagickpythonmagick

Set sampling algo


Im trying to create a thumbnail from a jpg image using PythonMagick:

img.quality(90)
# TODO set the sampling algo e.g. bilinear
img.sample(Geometry(scaledWid, scaledHei))
img.crop(Geometry(THUMBNAIL_WID-1, THUMBNAIL_HEI-1,cropLeft, cropTop))
img.write(destFilePath)

How do I set the sampling algo to be used? I believe right now it is using nearest neighbor which kinda looks ugly.


Solution

  • The resizing filter is set via a property on the image set before calling .resize() or, I imagine, .sample().

    The property is .filterType() and is set from one of the enumerated values on PythonMagick.FilterTypes - which is the same list as the Magick++ FilterTypes.

    (NB. There is never any documentation for PythonMagick, but as it's essentially just a wrapper for Magick++, just use the API documentation for that.)

    So try (untested, I don't use Python):

    img.quality(90)
    
    img.filterType(PythonMagick.FilterTypes.SincFilter)
    img.sample(Geometry(scaledWid, scaledHei))
    
    img.crop(Geometry(THUMBNAIL_WID-1, THUMBNAIL_HEI-1,cropLeft, cropTop))
    
    img.write(destFilePath)
    

    Note the default filter is usually LanczosFilter, or at least it is supposed to be, which is pretty good.