Mengekstrak gambar dari file PDF menggunakan Java
Contents
[
Hide
]
Aspose.PDF for Java mendukung ekstraksi sumber gambar langsung dan penyaringan berbasis penempatan.
Mengekstrak gambar tersemat berdasarkan indeks
Gunakan contoh ini ketika Anda perlu menyimpan sumber gambar tertentu dari halaman PDF
- Buka PDF sumber
Document. - Akses
XImagetarget dari sumber daya halaman. - Simpan aliran gambar ke file output.
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);
}
}
Mengekstrak gambar dari area halaman tertentu
Gunakan contoh ini ketika hanya gambar yang ditempatkan di dalam persegi panjang yang dipilih yang harus diekspor.
- Tentukan
Rectangletarget dan buka PDF sumber. - Gunakan
ImagePlacementAbsorberuntuk memeriksa penempatan gambar pada halaman. - Simpan hanya gambar yang penempatannya cocok di dalam wilayah yang dipilih.
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++;
}
}
}
}