首页 > 解决方案 > 从 pptx 下载 WMF 并解码为 JPEG

问题描述

你好 stackoverflow 用户。

我正在尝试从 powerpoint 演示文稿中下载图像,然后对其进行处理(以在特定坐标处识别其上的数字)。

我的问题是我只能从 .wmf 格式的 pptx 数据中下载图像,并且无法转换。我已经尝试了所有可能的解决方案。

from pptx import Presentation
from pptx.enum.shapes import MSO_SHAPE_TYPE

pptx_path = "name_pptx.pptx"

prs = Presentation(pptx_path)

desired_slide = prs.slides[6 - 1]

for shape in desired_slide.shapes:
    if shape.shape_type == MSO_SHAPE_TYPE.PICTURE:
        image_file_bytes = shape.image.blob
        file_extension = shape.image.ext # at this point format is .wfm

有趣的是,在 Powerpoint 中,我可以在保存文件时选择所需的 .jpeg 扩展名。

标签: pythonopencvpython-imaging-library

解决方案


我花了几个小时才解决我的问题,在 Windows 中将 wmf 文件转换为 jpg 有点棘手。我将图像添加到临时 excel 文件中,然后从中下载图像。

class ExcelHelpers():
    @staticmethod
    def add_img_to_excel(path_to_wmf):
        import xlsxwriter

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

    worksheet.insert_image('A1', path_to_wmf)

    workbook.close()

    @staticmethod
    def get_img_from_excel(long_filename):
        filename = os.path.basename(long_filename).split('.')[0]
        from PIL import ImageGrab
        import win32com.client as win32

        excel = win32.gencache.EnsureDispatch('Excel.Application')
        path_to_excel = os.path.join(os.getcwd(), 'test.xlsx')

        workbook = excel.Workbooks.Open(path_to_excel)

        for sheet in workbook.Worksheets:
            for i, shape in enumerate(sheet.Shapes):
                if shape.Name.startswith('Picture'):
                    shape.Copy()
                    image = ImageGrab.grabclipboard()
                    image.save('{}.jpg'.format(filename), 'jpeg')

        workbook.Close()
        excel.Quit()
        del excel
        os.remove(long_filename)
        os.remove('test.xlsx')

推荐阅读