Java を使用した PDF ファイルから画像の抽出

Aspose.PDF for Java は、直接的な画像リソース抽出および配置ベースのフィルタリングをサポートしています。

インデックスで埋め込まれた画像の抽出

PDF ページから特定の画像リソースを保存する必要がある場合に、この例を使用してください。

  1. ソース PDF の Document を開いてください。
  2. ページリソースから対象の XImage にアクセスしてください。
  3. 画像ストリームを出力ファイルに保存してください。
public static void extractImage(Path inputFile, Path outputFile) throws Exception {
    try (Document document = new Document(inputFile.toString());
         OutputStream outputImage = Files.newOutputStream(outputFile)) {
        XImage image = document.getPages().get_Item(1).getResources().getImages().get_Item(1);
        image.save(outputImage);
    }
}

特定のページ領域から画像の抽出

選択した矩形内に配置された画像のみをエクスポートする場合にこの例を使用してください。

  1. 対象領域を Rectangle で定義し、ソース PDF を開いてください。
  2. ImagePlacementAbsorber を使用して、ページ上の画像配置を検査してください。
  3. 選択領域内に完全に収まる画像のみを保存してください。
public static void extractImageFromSpecificRegion(Path inputFile, Path outputFile) throws Exception {
    Rectangle rectangle = new Rectangle(0, 0, 590, 590, true);

    try (Document document = new Document(inputFile.toString())) {
        ImagePlacementAbsorber absorber = new ImagePlacementAbsorber();
        document.getPages().get_Item(1).accept(absorber);
        int index = 1;
        for (ImagePlacement imagePlacement : absorber.getImagePlacements()) {
            Point point1 = new Point(imagePlacement.getRectangle().getLLX(), imagePlacement.getRectangle().getLLY());
            Point point2 = new Point(imagePlacement.getRectangle().getURX(), imagePlacement.getRectangle().getURX());
            if (rectangle.contains(point1, true) && rectangle.contains(point2, true)) {
                Path indexedOutputFile = Path.of(outputFile.toString().replace("index", String.valueOf(index)));
                try (OutputStream outputImage = Files.newOutputStream(indexedOutputFile)) {
                    imagePlacement.getImage().save(outputImage);
                }
                index++;
            }
        }
    }
}