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

从文档中 , insert_image函数采用以下选项:

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

问题是我需要插入的input图像的大小可能会有所不同,但他们需要的单元格的大小是固定的。 是否有可能以某种方式提供一个宽度和高度,让Excelresize的图像到提供的尺寸?

您可以使用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%来获取原始图像。

我不认为它有一个内置的方式来做规模,并保持高宽比。 你将不得不自己计算。

如果您想调整目标分辨率并提交文件(可能保持文件大小xlsxwriter ),请使用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})