0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PythonでPowerPointから画像を抽出する

Posted at

PowerPointドキュメントには通常、テキストの内容を説明するために多くの画像が含まれており、時には他の目的のためにこれらの画像を抽出する必要があるかもしれません。手動で画像を一つずつ保存する代わりに、この記事ではPythonを使ってプログラムでPowerPointプレゼンテーションから画像を抽出する方法を紹介します。

PowerPointファイルを処理するためのPythonライブラリ

PPT/PPTXファイルから画像を抽出するには、サードパーティライブラリSpire.Presentation for Pythonが必要です。pipコマンドでインストールできます。

pip install Spire.Presentation

PythonでPowerPointファイルから画像を抽出する

PowerPointプレゼンテーションのすべての画像を抽出するには、すべての画像を反復処理し、指定されたファイルパスにそれぞれを保存する必要があります。以下はその手順である:

  1. LoadFromFile() メソッドを使用して PowerPoint ファイルをロードする。
  2. Presentation.Images プロパティを使用して、ファイル内のすべての画像を取得します。
  3. 各画像を繰り返し処理し、指定したファイルパスに保存する。

Pythonコード:

from spire.presentation.common import *
from spire.presentation import *

# PowerPointドキュメントを読み込む
ppt = Presentation()
ppt.LoadFromFile("sampleR.pptx")

# ドキュメント内のすべての画像を反復処理する
for i, image in enumerate(ppt.Images):

    # 指定したファイルパスに画像を保存する
    ImageName = "ExtractImage/Images_"+str(i)+".png"
    image.Image.Save(ImageName)

ppt.Dispose()

ExtractPPTimage.png

Pythonで特定のスライドから画像を抽出する

特定のスライドから画像を抽出するには、スライド上のすべてのシェイプを繰り返し処理し、SlidePicture または PictureShape タイプのシェイプを見つけ、画像ファイルとして保存する必要があります。以下はその手順である:

  1. LoadFromFile() メソッドを使用して PowerPoint ファイルをロードする。
  2. Presentation.Slides[] プロパティで指定したスライドを取得します。
  3. スライド上のすべての図形をループします。
  4. 図形が SlidePicture 型か PictureShape 型かを判定する。
  5. 指定したファイルパスに画像を保存する。

Pythonコード:

from spire.presentation.common import *
from spire.presentation import *

# PowerPointドキュメントを読み込む
ppt = Presentation()
ppt.LoadFromFile("sampleR.pptx")

# 指定したスライドを取得する
slide = ppt.Slides[1]

i = 0
# スライド内のすべての形状をトラバースする
for s in slide.Shapes:

    # シェイプがSlidePictureタイプかどうかを判定する
    if isinstance(s, SlidePicture):

        # 画像を取り出す
        ps = s if isinstance(s, SlidePicture) else None
        ps.PictureFill.Picture.EmbedImage.Image.Save("Output/slide_"+str(i)+".png")
        i += 1

    # シェイプがPictureShapeタイプかどうかを判定する
    if isinstance(s, PictureShape):

        # 画像を取り出す
        ps = s if isinstance(s, PictureShape) else None
        ps.EmbedImage.Image.Save("Output/slide_"+str(i)+".png")
        i += 1

ppt.Dispose()

ExtractSlideImage.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?