Python を使用して PDF ファイルから画像を抽出する
Contents
[
Hide
]
このページは、埋め込まれたグラフィックを再利用したり、画像アセットをアーカイブしたり、PDF 以外の画像コンテンツを処理したりする必要がある場合に使用します。
- ソース PDF を以下のようにロードします。
ap.Document(infile). - ターゲットページとイメージリソースインデックスを選択します。
- イメージオブジェクトを出力ストリームに保存します。
import aspose.pdf as ap
from io import FileIO
def extract_image(infile, outfile):
document = ap.Document(infile)
x_image = document.pages[1].resources.images[1]
with FileIO(outfile, "wb") as output_image:
x_image.save(output_image)
PDF の特定の領域から画像を抽出
この例は、PDF ページの指定された矩形領域内にある画像を抽出し、それらを個別のファイルとして保存します。
- ソース PDF をロードします。
- 作成
ImagePlacementAbsorberターゲットページで受け入れてください。 - ターゲットの長方形を定義します。
- 画像の配置を繰り返して、各画像の境界が領域に収まるかどうかを確認します。
- 一致した画像を出力ファイルに保存します。
import aspose.pdf as ap
from io import FileIO
def extract_image_from_specific_region(infile, outfile):
document = ap.Document(infile)
rectangle = ap.Rectangle(0, 0, 590, 590, True)
absorber = ap.ImagePlacementAbsorber()
document.pages[1].accept(absorber)
index = 1
for image_placement in absorber.image_placements:
point1 = ap.Point(image_placement.rectangle.llx, image_placement.rectangle.lly)
point2 = ap.Point(image_placement.rectangle.urx, image_placement.rectangle.ury)
if rectangle.contains(point1, True) and rectangle.contains(point2, True):
with FileIO(outfile.replace("index", str(index)), "wb") as output_image:
image_placement.image.save(output_image)
index += 1