我不認爲它有一個內置的方式來做規模和保持寬高比。你將不得不自己計算。
如果要調整,並在目標分辨率提交的文件(可能是讓你的文件大小向下),與xlsxwriter
image_data
選項一起使用pillow
的thumbnail()
圖像的方法:
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})
如果您
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})
你想拉伸圖像或保持縱橫比嗎? – KobeJohn
我想縮小圖像,同時可能保持寬高比不變。但圖像的尺寸保持不變 - 特別是高度。 – Unos