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

Uno*_*nos 4 python excel xlsxwriter

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

{
    'x_offset':    0,
    'y_offset':    0,
    'x_scale':     1,
    'y_scale':     1,
    'url':         None,
    'tip':         None,
    'image_data':  None,
    'positioning': None,
}
Run Code Online (Sandbox Code Playgroud)

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

jmc*_*ara 8

可以在外部或Excel使用XlsxWriter内和缩放图像x_scaley_scale基于所述高度和孔隙(S)的宽度和形象。

例如:

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()
Run Code Online (Sandbox Code Playgroud)

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


Kob*_*ohn 5

我认为它没有内置的方法可以进行缩放并保持纵横比。您将必须自己计算。

如果要调整,并在目标分辨率提交的文件(可能是让你的文件大小下),使用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})
Run Code Online (Sandbox Code Playgroud)

如果要保留原始分辨率,并让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})
Run Code Online (Sandbox Code Playgroud)