通过 worksheet.insert_image 插入时设置图像的宽度和高度

Set width and height of an image when inserting via worksheet.insert_image

docs 开始,insert_image 函数采用以下选项:

{
    'x_offset':    0,
    'y_offset':    0,
    'x_scale':     1,
    'y_scale':     1,
    'url':         None,
    'tip':         None,
    'image_data':  None,
    'positioning': None,
}

问题是我需要插入的输入图像的大小可能会有所不同,但它们需要插入的单元格的大小是固定的。是否可以以某种方式提供宽度和高度并让 Excel 将图像调整为提供的尺寸?

我认为它没有内置的方式来缩放和保持纵横比。你得自己算。

如果您想调整大小并以目标分辨率提交文件(可能会减小文件大小),请使用 pillowthumbnail() 图像方法和 xlsxwriter image_data选项:

import io
from PIL import Image

def get_resized_image_data(file_path, bound_width_height):
    # get the image and resize it
    im = Image.open(file_path)
    im.thumbnail(bound_width_height, Image.ANTIALIAS)  # ANTIALIAS is important if shrinking

    # stuff the image data into a bytestream that excel can read
    im_bytes = io.BytesIO()
    im.save(im_bytes, format='PNG')
    return im_bytes

# use with xlsxwriter
image_path = 'asdf.png'
bound_width_height = (240, 240)
image_data = get_resized_image_data(image_path, bound_width_height)

# sanity check: remove these three lines if they cause problems
im = Image.open(image_data)
im.show()  # test if it worked so far - it does for me
im.seek(0)  # reset the "file" for excel to read it.

worksheet.insert_image(cell, image_path, {'image_data': image_data})

如果您想保持原始分辨率并让 excel 进行内部缩放但又适合您提供的范围,您可以在将其提供给 excel 之前计算正确的缩放因子:

from PIL import Image


def calculate_scale(file_path, bound_size):
    # check the image size without loading it into memory
    im = Image.open(file_path)
    original_width, original_height = im.size

    # calculate the resize factor, keeping original aspect and staying within boundary
    bound_width, bound_height = bound_size
    ratios = (float(bound_width) / original_width, float(bound_height) / original_height)
    return min(ratios)

# use with xlsxwriter
image_path = 'asdf.png'
bound_width_height = (240, 240)
resize_scale = calculate_scale(image_path, bound_width_height)
worksheet.insert_image(cell, image_path, {'x_scale': resize_scale, 'y_scale': resize_scale})

您可以使用 XlsxWriter 以及 x_scaley_scale 根据单元格和图像的高度和宽度在外部或 Excel 内缩放图像。

例如:

import xlsxwriter

workbook = xlsxwriter.Workbook('image_scaled.xlsx')
worksheet = workbook.add_worksheet()

image_width = 140.0
image_height = 182.0

cell_width = 64.0
cell_height = 20.0

x_scale = cell_width/image_width
y_scale = cell_height/image_height

worksheet.insert_image('B2', 'python.png',
                       {'x_scale': x_scale, 'y_scale': y_scale})

workbook.close()

这样缩放的好处是用户可以通过在 Excel 中将缩放设置回 100% 来恢复原始图像。