如何在openpyxl中提升插入Excel图片的分辨率?
问题原因与解决方案
问题原因
openpyxl在插入图片时默认会触发自动压缩或缩放逻辑:
- 若你设置的
ext尺寸和图片实际像素尺寸不匹配,openpyxl会自动缩放图片适配指定尺寸,直接导致分辨率下降。 - 即便尺寸匹配,openpyxl默认也会启用图片压缩优化,以减小Excel文件体积为目标降低图片质量。
解决方法
1. 确保插入尺寸与图片实际像素匹配
先读取原始图片的像素尺寸,将AbsoluteAnchor的ext参数转换为Excel兼容的物理尺寸,避免自动缩放。示例代码:
from openpyxl import Workbook from openpyxl.drawing.image import Image from openpyxl.drawing.geometry import AbsoluteAnchor from openpyxl.utils.units import pixels_to_EMU from PIL import Image as PILImage wb = Workbook() ws = wb.active # 读取原始图片,获取像素尺寸 pil_img = PILImage.open('high_resolution_image.png') width_px, height_px = pil_img.size # 转换为Excel使用的EMU单位 width_emu = pixels_to_EMU(width_px) height_emu = pixels_to_EMU(height_px) # 创建Image对象并设置匹配尺寸 img = Image('high_resolution_image.png') img.anchor = AbsoluteAnchor(pos=position, ext=(width_emu, height_emu)) ws.add_image(img) wb.save('result.xlsx')
2. 禁用图片压缩
针对不同格式的图片,调整openpyxl的压缩参数以保留原始质量:
- PNG格式:设置
img.image.compression = 0(0代表无压缩) - JPEG格式:设置
img.image.quality = 100(100为最高质量)
修改后的代码示例:
from openpyxl import Workbook from openpyxl.drawing.image import Image from openpyxl.drawing.geometry import AbsoluteAnchor wb = Workbook() ws = wb.active img = Image('high_resolution_image.png') img.anchor = AbsoluteAnchor(pos=position, ext=size) # 根据图片格式设置压缩参数 if img.format == 'PNG': img.image.compression = 0 elif img.format == 'JPEG': img.image.quality = 100 ws.add_image(img) wb.save('result.xlsx')
3. 直接插入原始图片数据(进阶)
如果前两种方法效果不佳,可以直接读取图片原始二进制数据,绕过openpyxl的自动处理逻辑:
from openpyxl import Workbook from openpyxl.drawing.image import Image from openpyxl.drawing.geometry import AbsoluteAnchor wb = Workbook() ws = wb.active # 读取原始图片二进制数据 with open('high_resolution_image.png', 'rb') as f: img_data = f.read() # 创建Image对象并加载原始数据 img = Image() img.image.load(img_data) img.anchor = AbsoluteAnchor(pos=position, ext=size) # 禁用PNG压缩 if img.format == 'PNG': img.image.compression = 0 ws.add_image(img) wb.save('result.xlsx')
内容的提问来源于stack exchange,提问作者Gilseung Ahn
相关产品推荐
相关产品推荐

