Win32 Excel: 将图像调整为保持纵横比的单元格

Win32 Excel: Resize image to cell maintaining aspect ratio

我正在编写一个脚本,给定图像及其包含的单元格应调整图像大小以适合该单元格,同时保持其纵横比。

该函数有 3 个参数,图像、单元格的宽度和单元格的高度。

到目前为止,我已经编写了以下函数:

def fitToCell(img, width, height):
    ratioX = width / img.Width
    ratioY = height / img.Height

    if ratioX * img.Height > height:
        ratio = ratioY
    else:
        ratio = ratioX

    img.Width = img.Width * ratio
    img.Height = img.Height * ratio

    return img

我的日志记录给出了以下结果:

Original Image: (48.0, 35.26598358154297)
Desired Image: (100, 100)
Ratios: (2.0833333333333335, 2.8355936753834547)
Final Ratio: 2.0833333333333335
Final Image: (208.33331298828125, 153.0640869140625)

这对我来说似乎没有任何意义,因为 2 * 48 = 96,而不是 208。该比率应该产生输出 100、73。

我在 xlsx 文件上使用 win32com api 和 Python。如果有任何建议,我将不胜感激。

这是我修改后的代码,可以达到想要的效果

我的编译环境是WIN10,python3.7

from PIL import Image 

def fitToCell(img, width, height):
  try:    
    ratioX = width / img.width
    ratioY = height / img.height

    if ratioX * img.height > height:
        ratio = ratioY
    else:
        ratio = ratioX

    Width = img.width * ratio
    Height = img.height * ratio

    print("Original Image :",img.width, img.height)
    print("Ratios :",ratioX, ratioY)
    print("Final Ratio :",ratio)
    print("Final Image :",Width, Height)
  except IOError: 
    pass


if __name__ == "__main__": 
  img  = Image.open("panda.jpg")
  fitToCell(img, 400, 400)

调试结果:

Original Image : 268 304
Ratios : 1.492537313432836 1.3157894736842106
Final Ratio : 1.3157894736842106
Final Image : 352.63157894736844 400.0

不同的是我用的是image module.

The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images.