pythonimageimagemagickwand

Python Wand how to resize keeping aspect ratio and filling in the remaining space with an transparency


I am trying to resize an image with python Wand preserving the aspect ratio and filling in the remaining location with a transparency. For example I would like to resize an large rectangle down to fit within 100x100 image while keeping the aspect ratio, but I would like to get a image returned back as 100x100 with a transparency filled into the gaps. Is this possible using Wand?

I tested out img.resize() and img.transform() and it seems to just preserve the aspect ratio but not the requested image size.

If Wand is not capable of doing this are there any other libraries that could?

Thanks for the help!


Solution

  • My solution was to create a blank outer image to lay the transformed image over. This results in the intended width and height, while fitting the image within those bounds preserving the aspect ratio.

    def resizeImg(sourceFile, destFile, width, height):                                                                                                                                                                                                                                       
      with Image(width=width, height=height) as outerImg:                                                                                                                                                                                                                                     
        with Image(filename=sourceFile) as img:                                                                                                                                                                                                                                               
          img.transform(resize="%dx%d>" % (width, height))                                                                                                                                                                                                                                    
          outerImg.format = img.format.lower()                                                                                                                                                                                                                                                
          outerImg.composite(img, left=(width - img.width) / 2, top=(height - img.height) / 2)                                                                                                                                                                                                
          outerImg.save(filename=destFile)