Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

Deduplicate extracted images by content hash (#7822)

Anthony Stirling77b850ac3cce
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/ExtractImagesController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/ExtractImagesController.java
index 3dfe1d6ba2..1efc277b3f 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/ExtractImagesController.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/ExtractImagesController.java
@@ -4,10 +4,19 @@ import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
+import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.ArrayList;
+import java.util.Comparator;
import java.util.HashSet;
+import java.util.HexFormat;
+import java.util.IdentityHashMap;
+import java.util.List;
+import java.util.Map;
import java.util.Set;
import java.util.zip.Deflater;
import java.util.zip.ZipEntry;
@@ -15,7 +24,13 @@ import java.util.zip.ZipOutputStream;
import javax.imageio.ImageIO;
+import org.apache.pdfbox.cos.COSArray;
+import org.apache.pdfbox.cos.COSBase;
+import org.apache.pdfbox.cos.COSDictionary;
import org.apache.pdfbox.cos.COSName;
+import org.apache.pdfbox.cos.COSObject;
+import org.apache.pdfbox.cos.COSStream;
+import org.apache.pdfbox.cos.COSString;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
@@ -50,6 +65,24 @@ import stirling.software.common.util.WebResponseUtils;
@RequiredArgsConstructor
public class ExtractImagesController {
+ private static final int MAX_KEY_DEPTH = 32;
+ private static final int MAX_KEY_NODES = 4096;
+
+ private static final Set<COSName> DECODE_RELEVANT_IMAGE_KEYS =
+ Set.of(
+ COSName.BITS_PER_COMPONENT,
+ COSName.COLORSPACE,
+ COSName.DECODE,
+ COSName.DECODE_PARMS,
+ COSName.FILTER,
+ COSName.HEIGHT,
+ COSName.IMAGE_MASK,
+ COSName.MASK,
+ COSName.MATTE,
+ COSName.SMASK,
+ COSName.SMASK_IN_DATA,
+ COSName.WIDTH);
+
private final CustomPDFDocumentFactory pdfDocumentFactory;
private final TempFileManager tempFileManager;
@@ -70,7 +103,7 @@ public class ExtractImagesController {
String imageFormat = request.getFormat();
String baseFilename = GeneralUtils.removeExtension(file.getOriginalFilename());
- Set<Integer> processedImageHashes = new HashSet<>();
+ ImageFingerprints fingerprints = new ImageFingerprints();
TempFile zipFile = new TempFile(tempFileManager, ".zip");
try (ZipOutputStream zipStream =
@@ -87,7 +120,7 @@ public class ExtractImagesController {
imageFormat,
baseFilename,
pageIndex + 1,
- processedImageHashes,
+ fingerprints,
zipStream);
}
} catch (Exception e) {
@@ -104,7 +137,7 @@ public class ExtractImagesController {
String imageFormat,
String baseFilename,
int pageNumber,
- Set<Integer> seenImageHashes,
+ ImageFingerprints fingerprints,
ZipOutputStream zipOutput)
throws IOException {
if (page.getResources() == null || page.getResources().getXObjectNames() == null) {
@@ -120,15 +153,13 @@ public class ExtractImagesController {
try {
PDImageXObject imageObject =
(PDImageXObject) page.getResources().getXObject(resourceName);
- int imageHashCode = imageObject.hashCode();
- if (seenImageHashes.contains(imageHashCode)) {
+ if (!fingerprints.isFirstOccurrence(imageObject)) {
continue;
}
- seenImageHashes.add(imageHashCode);
RenderedImage sourceImage = imageObject.getImage();
- BufferedImage convertedImage = convertImageToFormat(sourceImage, imageFormat);
+ RenderedImage outputImage = toWritableImage(sourceImage, imageFormat);
String imagePath =
baseFilename
@@ -138,11 +169,14 @@ public class ExtractImagesController {
+ imageCount++
+ "."
+ imageFormat;
- ByteArrayOutputStream imageBuffer = new ByteArrayOutputStream();
- ImageIO.write(convertedImage, imageFormat, imageBuffer);
zipOutput.putNextEntry(new ZipEntry(imagePath));
- zipOutput.write(imageBuffer.toByteArray());
+ if (!ImageIO.write(outputImage, imageFormat, zipOutput)) {
+ throw ExceptionUtils.createIllegalArgumentException(
+ "error.unsupportedImageFormat",
+ "No image writer is available for format {0}.",
+ imageFormat);
+ }
zipOutput.closeEntry();
} catch (IOException e) {
@@ -152,16 +186,172 @@ public class ExtractImagesController {
}
}
- private BufferedImage convertImageToFormat(RenderedImage source, String format) {
- int width = source.getWidth();
- int height = source.getHeight();
+ /**
+ * Per-document dedup state. A fingerprint is memoised against the image's COS object, so an
+ * XObject drawn on every page is digested once for the document rather than once per page, and
+ * an image that cannot be fingerprinted falls back to a key unique to that COS object, so it
+ * deduplicates against itself without ever colliding with another image.
+ */
+ static final class ImageFingerprints {
+
+ private final Map<COSBase, String> keysByImage = new IdentityHashMap<>();
+ private final Set<String> extracted = new HashSet<>();
+ private int unfingerprintableImages;
+ private boolean failureLogged;
+
+ boolean isFirstOccurrence(PDImageXObject image) {
+ return extracted.add(keyFor(image));
+ }
+
+ String keyFor(PDImageXObject image) {
+ COSBase imageCos = image.getCOSObject();
+ String key = keysByImage.get(imageCos);
+ if (key == null) {
+ key = fingerprint(image);
+ keysByImage.put(imageCos, key);
+ }
+ return key;
+ }
+
+ private String fingerprint(PDImageXObject image) {
+ try {
+ return imageContentKey(image);
+ } catch (IOException | NoSuchAlgorithmException | RuntimeException e) {
+ if (!failureLogged) {
+ failureLogged = true;
+ log.warn("Could not fingerprint embedded image, deduplicating by identity", e);
+ }
+ return "identity:" + unfingerprintableImages++;
+ }
+ }
+ }
+
+ /**
+ * Content fingerprint identifying one embedded image, used to extract a repeated image only
+ * once. Folds in the encoded stream and the image dictionary entries decoding depends on -
+ * filters, colour space, decode array and masks - with indirect references resolved, so two
+ * copies of the same image match while two images that merely share encoded bytes do not.
+ * Entries that leave the decoded pixels unchanged, such as metadata and optional content, are
+ * ignored so they cannot defeat the dedup.
+ *
+ * @throws IOException when a stream cannot be read, or the object graph exceeds the walk's node
+ * budget; the caller must fall back rather than treat the image as unique
+ */
+ private static String imageContentKey(PDImageXObject image)
+ throws IOException, NoSuchAlgorithmException {
+ MessageDigest digest = MessageDigest.getInstance("SHA-256");
+ KeyWalk walk = new KeyWalk();
+ digestValue(digest, image.getCOSObject(), walk, 0);
+ if (!image.isStencil()) {
+ digestValue(digest, image.getColorSpace().getCOSObject(), walk, 0);
+ }
+ return HexFormat.of().formatHex(digest.digest());
+ }
+
+ /**
+ * Bounds one fingerprint walk. An indirect object is expanded at most once per walk and the
+ * whole walk is capped at {@code MAX_KEY_NODES} nodes, so a shared sub-graph cannot be
+ * re-walked once per incoming edge and a crafted graph cannot fan out exponentially within the
+ * depth cap.
+ */
+ private static final class KeyWalk {
+
+ private final Set<Long> expanded = new HashSet<>();
+ private int remainingNodes = MAX_KEY_NODES;
+
+ private void enterNode() throws IOException {
+ if (--remainingNodes < 0) {
+ throw new IOException(
+ "image object graph exceeds " + MAX_KEY_NODES + " fingerprint nodes");
+ }
+ }
+ }
+
+ private static void digestValue(MessageDigest digest, COSBase value, KeyWalk walk, int depth)
+ throws IOException {
+ if (value == null || depth > MAX_KEY_DEPTH) {
+ digest.update((byte) 'x');
+ return;
+ }
+ walk.enterNode();
+ switch (value) {
+ case COSObject reference -> {
+ if (!walk.expanded.add(reference.getObjectNumber())) {
+ digest.update((byte) 'c');
+ return;
+ }
+ digestValue(digest, reference.getObject(), walk, depth + 1);
+ }
+ case COSStream stream -> {
+ digest.update((byte) 's');
+ try (InputStream raw = stream.createRawInputStream()) {
+ byte[] buffer = new byte[8192];
+ for (int read; (read = raw.read(buffer)) != -1; ) {
+ digest.update(buffer, 0, read);
+ }
+ }
+ digestDictionary(digest, stream, walk, depth);
+ }
+ case COSDictionary dictionary -> {
+ digest.update((byte) 'd');
+ digestDictionary(digest, dictionary, walk, depth);
+ }
+ case COSArray array -> {
+ digest.update((byte) 'a');
+ for (int i = 0; i < array.size(); i++) {
+ digestValue(digest, array.get(i), walk, depth + 1);
+ }
+ }
+ case COSString text -> {
+ digest.update((byte) 't');
+ digest.update(text.getBytes());
+ }
+ case COSName name -> {
+ digest.update((byte) 'n');
+ digest.update(name.getName().getBytes(StandardCharsets.UTF_8));
+ }
+ default -> {
+ digest.update((byte) 'v');
+ digest.update(value.toString().getBytes(StandardCharsets.UTF_8));
+ }
+ }
+ }
+
+ private static void digestDictionary(
+ MessageDigest digest, COSDictionary dictionary, KeyWalk walk, int depth)
+ throws IOException {
+ boolean imageDictionary = COSName.IMAGE.equals(dictionary.getCOSName(COSName.SUBTYPE));
+ List<COSName> keys = new ArrayList<>(dictionary.keySet());
+ keys.sort(Comparator.comparing(COSName::getName));
+ for (COSName key : keys) {
+ if (COSName.LENGTH.equals(key)) {
+ continue;
+ }
+ if (imageDictionary && !DECODE_RELEVANT_IMAGE_KEYS.contains(key)) {
+ continue;
+ }
+ digest.update(key.getName().getBytes(StandardCharsets.UTF_8));
+ digestValue(digest, dictionary.getItem(key), walk, depth + 1);
+ }
+ }
+
+ /**
+ * Returns an image ImageIO can write in {@code format}, reusing {@code source} when it is
+ * already compatible. Redrawing costs a second full-size buffer, so it is avoided when the
+ * decoded image already has the type the format needs.
+ */
+ private RenderedImage toWritableImage(RenderedImage source, String format) {
+ int requiredType =
+ "png".equalsIgnoreCase(format)
+ ? BufferedImage.TYPE_INT_ARGB
+ : BufferedImage.TYPE_INT_RGB;
- int imageType = BufferedImage.TYPE_INT_RGB;
- if ("png".equalsIgnoreCase(format)) {
- imageType = BufferedImage.TYPE_INT_ARGB;
+ if (source instanceof BufferedImage buffered && buffered.getType() == requiredType) {
+ return buffered;
}
- BufferedImage result = new BufferedImage(width, height, imageType);
+ BufferedImage result =
+ new BufferedImage(source.getWidth(), source.getHeight(), requiredType);
Graphics2D graphics = result.createGraphics();
graphics.drawImage((Image) source, 0, 0, null);
graphics.dispose();
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/ExtractImagesControllerTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/ExtractImagesControllerTest.java
index 0e428b9747..4c5a3d6a25 100644
--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/ExtractImagesControllerTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/ExtractImagesControllerTest.java
@@ -3,13 +3,27 @@ package stirling.software.SPDF.controller.api.misc;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
+import java.awt.Color;
+import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
+import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
+import java.security.MessageDigest;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+import javax.imageio.ImageIO;
import org.apache.pdfbox.Loader;
+import org.apache.pdfbox.cos.COSDictionary;
+import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
@@ -21,6 +35,8 @@ import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.InjectMocks;
import org.mockito.Mock;
+import org.mockito.MockedStatic;
+import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
@@ -71,6 +87,192 @@ class ExtractImagesControllerTest {
Files.readAllBytes(path));
}
+ private MockMultipartFile createPdfRepeatingOneImage(int pageCount) throws IOException {
+ Path path = tempDir.resolve("repeated.pdf");
+ try (PDDocument doc = new PDDocument()) {
+ BufferedImage img = new BufferedImage(60, 40, BufferedImage.TYPE_INT_RGB);
+ img.createGraphics().fillRect(0, 0, 60, 40);
+ PDImageXObject pdImage = JPEGFactory.createFromImage(doc, img);
+ for (int i = 0; i < pageCount; i++) {
+ PDPage page = new PDPage(PDRectangle.LETTER);
+ doc.addPage(page);
+ try (PDPageContentStream cs = new PDPageContentStream(doc, page)) {
+ cs.drawImage(pdImage, 50, 600, 100, 100);
+ }
+ }
+ doc.save(path.toFile());
+ }
+ return new MockMultipartFile(
+ "fileInput",
+ "repeated.pdf",
+ MediaType.APPLICATION_PDF_VALUE,
+ Files.readAllBytes(path));
+ }
+
+ private MockMultipartFile createPdfWithDistinctImages(int count) throws IOException {
+ Path path = tempDir.resolve("distinct.pdf");
+ try (PDDocument doc = new PDDocument()) {
+ for (int i = 0; i < count; i++) {
+ PDPage page = new PDPage(PDRectangle.LETTER);
+ doc.addPage(page);
+ BufferedImage img = new BufferedImage(60, 40, BufferedImage.TYPE_INT_RGB);
+ Graphics2D g = img.createGraphics();
+ g.setColor(new Color(20 + i * 70, 40 + i * 50, 200 - i * 60));
+ g.fillRect(0, 0, 60, 40);
+ g.dispose();
+ PDImageXObject pdImage = JPEGFactory.createFromImage(doc, img);
+ try (PDPageContentStream cs = new PDPageContentStream(doc, page)) {
+ cs.drawImage(pdImage, 50, 600, 100, 100);
+ }
+ }
+ doc.save(path.toFile());
+ }
+ return new MockMultipartFile(
+ "fileInput",
+ "distinct.pdf",
+ MediaType.APPLICATION_PDF_VALUE,
+ Files.readAllBytes(path));
+ }
+
+ private List<String> extractedEntryNames(MockMultipartFile file, String format)
+ throws IOException {
+ return new ArrayList<>(extractedEntries(file, format).keySet());
+ }
+
+ private Map<String, byte[]> extractedEntries(MockMultipartFile file, String format)
+ throws IOException {
+ PDFExtractImagesRequest request = new PDFExtractImagesRequest();
+ request.setFileInput(file);
+ request.setFormat(format);
+
+ when(pdfDocumentFactory.load(file)).thenReturn(Loader.loadPDF(file.getBytes()));
+ when(tempFileManager.createTempFile(anyString()))
+ .thenAnswer(inv -> createTempFile(inv.getArgument(0)));
+
+ var response = controller.extractImages(request);
+ assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
+
+ Map<String, byte[]> entries = new LinkedHashMap<>();
+ try (ZipInputStream zis = new ZipInputStream(response.getBody().getInputStream())) {
+ for (ZipEntry entry = zis.getNextEntry(); entry != null; entry = zis.getNextEntry()) {
+ entries.put(entry.getName(), zis.readAllBytes());
+ }
+ }
+ return entries;
+ }
+
+ /**
+ * The image carries an object graph too large to fingerprint, so extraction falls back to
+ * identity rather than treating every occurrence as a new image.
+ */
+ private MockMultipartFile createPdfWithUnfingerprintableImage(int pageCount)
+ throws IOException {
+ Path path = tempDir.resolve("unfingerprintable.pdf");
+ try (PDDocument doc = new PDDocument()) {
+ BufferedImage img = new BufferedImage(60, 40, BufferedImage.TYPE_INT_RGB);
+ PDImageXObject pdImage = JPEGFactory.createFromImage(doc, img);
+ COSDictionary oversized = new COSDictionary();
+ for (int i = 0; i < 5000; i++) {
+ oversized.setInt(COSName.getPDFName("K" + i), i);
+ }
+ pdImage.getCOSObject().setItem(COSName.DECODE_PARMS, oversized);
+ for (int i = 0; i < pageCount; i++) {
+ PDPage page = new PDPage(PDRectangle.LETTER);
+ doc.addPage(page);
+ try (PDPageContentStream cs = new PDPageContentStream(doc, page)) {
+ cs.drawImage(pdImage, 50, 600, 100, 100);
+ }
+ }
+ doc.save(path.toFile());
+ }
+ return new MockMultipartFile(
+ "fileInput",
+ "unfingerprintable.pdf",
+ MediaType.APPLICATION_PDF_VALUE,
+ Files.readAllBytes(path));
+ }
+
+ /**
+ * Byte-identical images embedded as separate COS objects, as merging two PDFs produces. Each
+ * page gets its own PDImageXObject, so identity-based dedup sees them as distinct.
+ */
+ private MockMultipartFile createPdfWithDuplicatedImageObjects(int pageCount)
+ throws IOException {
+ Path path = tempDir.resolve("duplicated.pdf");
+ BufferedImage img = new BufferedImage(60, 40, BufferedImage.TYPE_INT_RGB);
+ Graphics2D g = img.createGraphics();
+ g.setColor(new Color(30, 90, 180));
+ g.fillRect(0, 0, 60, 40);
+ g.dispose();
+
+ try (PDDocument doc = new PDDocument()) {
+ for (int i = 0; i < pageCount; i++) {
+ PDPage page = new PDPage(PDRectangle.LETTER);
+ doc.addPage(page);
+ PDImageXObject pdImage = JPEGFactory.createFromImage(doc, img);
+ try (PDPageContentStream cs = new PDPageContentStream(doc, page)) {
+ cs.drawImage(pdImage, 50, 600, 100, 100);
+ }
+ }
+ doc.save(path.toFile());
+ }
+ return new MockMultipartFile(
+ "fileInput",
+ "duplicated.pdf",
+ MediaType.APPLICATION_PDF_VALUE,
+ Files.readAllBytes(path));
+ }
+
+ @Test
+ void extractImages_sameImageOnEveryPage_extractedOnce() throws IOException {
+ assertThat(extractedEntryNames(createPdfRepeatingOneImage(5), "png")).hasSize(1);
+ }
+
+ @Test
+ void extractImages_duplicatedImageObjects_extractedOnce() throws IOException {
+ assertThat(extractedEntryNames(createPdfWithDuplicatedImageObjects(4), "png")).hasSize(1);
+ }
+
+ @Test
+ void extractImages_unfingerprintableImageOnEveryPage_extractedOnce() throws IOException {
+ assertThat(extractedEntryNames(createPdfWithUnfingerprintableImage(5), "png")).hasSize(1);
+ }
+
+ @Test
+ void extractImages_sameImageOnEveryPage_fingerprintedOncePerDocument() throws IOException {
+ MockMultipartFile file = createPdfRepeatingOneImage(6);
+ PDFExtractImagesRequest request = new PDFExtractImagesRequest();
+ request.setFileInput(file);
+ request.setFormat("png");
+
+ when(pdfDocumentFactory.load(file)).thenReturn(Loader.loadPDF(file.getBytes()));
+ when(tempFileManager.createTempFile(anyString()))
+ .thenAnswer(inv -> createTempFile(inv.getArgument(0)));
+
+ try (MockedStatic<MessageDigest> digests =
+ mockStatic(MessageDigest.class, Mockito.CALLS_REAL_METHODS)) {
+ controller.extractImages(request);
+ digests.verify(() -> MessageDigest.getInstance("SHA-256"), times(1));
+ }
+ }
+
+ @Test
+ void extractImages_writesReadableImageOfSourceSize() throws IOException {
+ Map<String, byte[]> entries = extractedEntries(createPdfRepeatingOneImage(2), "png");
+ assertThat(entries).hasSize(1);
+
+ byte[] written = entries.values().iterator().next();
+ BufferedImage image = ImageIO.read(new ByteArrayInputStream(written));
+ assertThat(image).isNotNull();
+ assertThat(image.getWidth()).isEqualTo(60);
+ assertThat(image.getHeight()).isEqualTo(40);
+ }
+
+ @Test
+ void extractImages_distinctImages_allExtracted() throws IOException {
+ assertThat(extractedEntryNames(createPdfWithDistinctImages(3), "png")).hasSize(3);
+ }
+
@Test
void extractImages_withImage_returnsZip() throws IOException {
MockMultipartFile file = createPdfWithImage();
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/ExtractImagesDedupKeyTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/ExtractImagesDedupKeyTest.java
new file mode 100644
index 0000000000..32ce6d789b
--- /dev/null
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/ExtractImagesDedupKeyTest.java
@@ -0,0 +1,363 @@
+package stirling.software.SPDF.controller.api.misc;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
+
+import java.awt.Color;
+import java.awt.Graphics2D;
+import java.awt.image.BufferedImage;
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.lang.reflect.Method;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.pdfbox.cos.COSArray;
+import org.apache.pdfbox.cos.COSDictionary;
+import org.apache.pdfbox.cos.COSFloat;
+import org.apache.pdfbox.cos.COSInteger;
+import org.apache.pdfbox.cos.COSName;
+import org.apache.pdfbox.cos.COSObject;
+import org.apache.pdfbox.cos.COSObjectKey;
+import org.apache.pdfbox.cos.COSString;
+import org.apache.pdfbox.pdmodel.PDDocument;
+import org.apache.pdfbox.pdmodel.graphics.color.PDDeviceGray;
+import org.apache.pdfbox.pdmodel.graphics.color.PDDeviceRGB;
+import org.apache.pdfbox.pdmodel.graphics.image.JPEGFactory;
+import org.apache.pdfbox.pdmodel.graphics.image.LosslessFactory;
+import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
+import org.junit.jupiter.api.Test;
+
+import stirling.software.SPDF.controller.api.misc.ExtractImagesController.ImageFingerprints;
+
+class ExtractImagesDedupKeyTest {
+
+ private static String key(PDImageXObject image) throws Exception {
+ Method m =
+ ExtractImagesController.class.getDeclaredMethod(
+ "imageContentKey", PDImageXObject.class);
+ m.setAccessible(true);
+ return (String) m.invoke(null, image);
+ }
+
+ private static BufferedImage solid(int type, Color c) {
+ BufferedImage img = new BufferedImage(40, 30, type);
+ Graphics2D g = img.createGraphics();
+ g.setColor(c);
+ g.fillRect(0, 0, 40, 30);
+ g.dispose();
+ return img;
+ }
+
+ @Test
+ void argbWithSoftMask_twoIdenticalEmbeds_sameKey() throws Exception {
+ try (PDDocument doc = new PDDocument()) {
+ BufferedImage img = solid(BufferedImage.TYPE_INT_ARGB, new Color(30, 90, 180, 128));
+ PDImageXObject a = LosslessFactory.createFromImage(doc, img);
+ PDImageXObject b = LosslessFactory.createFromImage(doc, img);
+ assertThat(a.getCOSObject().getItem(COSName.SMASK)).isNotNull();
+ assertThat(key(a)).isEqualTo(key(b));
+ }
+ }
+
+ @Test
+ void sameBytesDifferentPalette_differentKeys() throws Exception {
+ try (PDDocument doc = new PDDocument()) {
+ byte[] raw = {0x00, 0x01, 0x00, 0x01};
+ PDImageXObject a =
+ new PDImageXObject(
+ doc,
+ new ByteArrayInputStream(raw),
+ COSName.FLATE_DECODE,
+ 4,
+ 1,
+ 8,
+ PDDeviceGray.INSTANCE);
+ PDImageXObject b =
+ new PDImageXObject(
+ doc,
+ new ByteArrayInputStream(raw),
+ COSName.FLATE_DECODE,
+ 4,
+ 1,
+ 8,
+ PDDeviceGray.INSTANCE);
+ a.getCOSObject()
+ .setItem(
+ COSName.COLORSPACE,
+ indexed(new byte[] {(byte) 0xFF, 0, 0, 0, (byte) 0xFF, 0}));
+ b.getCOSObject()
+ .setItem(
+ COSName.COLORSPACE,
+ indexed(new byte[] {0, 0, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, 0}));
+ assertThat(key(a)).isNotEqualTo(key(b));
+ }
+ }
+
+ @Test
+ void sameBytesDifferentDecodeParms_differentKeys() throws Exception {
+ try (PDDocument doc = new PDDocument()) {
+ byte[] raw = {0x02, 0x0A, 0x14, 0x1E};
+ PDImageXObject a =
+ new PDImageXObject(
+ doc,
+ new ByteArrayInputStream(raw),
+ COSName.FLATE_DECODE,
+ 4,
+ 1,
+ 8,
+ PDDeviceGray.INSTANCE);
+ PDImageXObject b =
+ new PDImageXObject(
+ doc,
+ new ByteArrayInputStream(raw),
+ COSName.FLATE_DECODE,
+ 4,
+ 1,
+ 8,
+ PDDeviceGray.INSTANCE);
+ org.apache.pdfbox.cos.COSDictionary parms = new org.apache.pdfbox.cos.COSDictionary();
+ parms.setInt(COSName.PREDICTOR, 12);
+ parms.setInt(COSName.COLORS, 1);
+ parms.setInt(COSName.COLUMNS, 4);
+ parms.setInt(COSName.BITS_PER_COMPONENT, 8);
+ b.getCOSObject().setItem(COSName.DECODE_PARMS, parms);
+ assertThat(key(a)).isNotEqualTo(key(b));
+ }
+ }
+
+ @Test
+ void sameBytesDifferentSoftMask_differentKeys() throws Exception {
+ try (PDDocument doc = new PDDocument()) {
+ BufferedImage base = solid(BufferedImage.TYPE_INT_RGB, new Color(10, 20, 30));
+ PDImageXObject a = JPEGFactory.createFromImage(doc, base);
+ PDImageXObject b = JPEGFactory.createFromImage(doc, base);
+ assertThat(key(a)).isEqualTo(key(b));
+
+ byte[] maskA = new byte[40 * 30];
+ byte[] maskB = new byte[40 * 30];
+ java.util.Arrays.fill(maskB, (byte) 0x7F);
+ b.getCOSObject()
+ .setItem(
+ COSName.SMASK,
+ new PDImageXObject(
+ doc,
+ new ByteArrayInputStream(maskB),
+ COSName.FLATE_DECODE,
+ 40,
+ 30,
+ 8,
+ PDDeviceGray.INSTANCE)
+ .getCOSObject());
+ a.getCOSObject()
+ .setItem(
+ COSName.SMASK,
+ new PDImageXObject(
+ doc,
+ new ByteArrayInputStream(maskA),
+ COSName.FLATE_DECODE,
+ 40,
+ 30,
+ 8,
+ PDDeviceGray.INSTANCE)
+ .getCOSObject());
+ assertThat(key(a)).isNotEqualTo(key(b));
+ }
+ }
+
+ @Test
+ void iccLikeIndirectColorSpace_twoIdenticalEmbeds_sameKey() throws Exception {
+ try (PDDocument doc = new PDDocument()) {
+ byte[] raw = {0x01, 0x02, 0x03, 0x04};
+ PDImageXObject a =
+ new PDImageXObject(
+ doc,
+ new ByteArrayInputStream(raw),
+ COSName.FLATE_DECODE,
+ 4,
+ 1,
+ 8,
+ PDDeviceRGB.INSTANCE);
+ PDImageXObject b =
+ new PDImageXObject(
+ doc,
+ new ByteArrayInputStream(raw),
+ COSName.FLATE_DECODE,
+ 4,
+ 1,
+ 8,
+ PDDeviceRGB.INSTANCE);
+ a.getCOSObject().setItem(COSName.COLORSPACE, indexed(new byte[] {1, 2, 3, 4, 5, 6}));
+ b.getCOSObject().setItem(COSName.COLORSPACE, indexed(new byte[] {1, 2, 3, 4, 5, 6}));
+ assertThat(key(a)).isEqualTo(key(b));
+ }
+ }
+
+ @Test
+ void sharedSubGraph_isWalkedOncePerObject() throws Exception {
+ try (PDDocument doc = new PDDocument()) {
+ PDImageXObject image =
+ new PDImageXObject(
+ doc,
+ new ByteArrayInputStream(new byte[] {0x01, 0x02, 0x03, 0x04}),
+ COSName.FLATE_DECODE,
+ 4,
+ 1,
+ 8,
+ PDDeviceGray.INSTANCE);
+ image.getCOSObject().setItem(COSName.DECODE_PARMS, sharedChild(16, 4));
+
+ assertTimeoutPreemptively(
+ Duration.ofSeconds(5), () -> assertThat(key(image)).isNotNull());
+ }
+ }
+
+ @Test
+ void oversizedObjectGraph_isRejectedRatherThanWalked() throws Exception {
+ try (PDDocument doc = new PDDocument()) {
+ PDImageXObject image =
+ new PDImageXObject(
+ doc,
+ new ByteArrayInputStream(new byte[] {0x01, 0x02, 0x03, 0x04}),
+ COSName.FLATE_DECODE,
+ 4,
+ 1,
+ 8,
+ PDDeviceGray.INSTANCE);
+ image.getCOSObject().setItem(COSName.DECODE_PARMS, wideDictionary(5000));
+
+ assertThatThrownBy(() -> key(image)).hasRootCauseInstanceOf(IOException.class);
+ }
+ }
+
+ @Test
+ void softMaskMatteOnlyDifference_differentKeys() throws Exception {
+ try (PDDocument doc = new PDDocument()) {
+ BufferedImage img = solid(BufferedImage.TYPE_INT_RGB, new Color(10, 20, 30));
+ PDImageXObject a = JPEGFactory.createFromImage(doc, img);
+ PDImageXObject b = JPEGFactory.createFromImage(doc, img);
+ a.getCOSObject().setItem(COSName.SMASK, softMask(doc).getCOSObject());
+
+ COSDictionary maskWithMatte = softMask(doc).getCOSObject();
+ COSArray matte = new COSArray();
+ matte.add(new COSFloat(0.25f));
+ matte.add(new COSFloat(0.5f));
+ matte.add(new COSFloat(0.75f));
+ maskWithMatte.setItem(COSName.MATTE, matte);
+ b.getCOSObject().setItem(COSName.SMASK, maskWithMatte);
+
+ assertThat(key(a)).isNotEqualTo(key(b));
+ }
+ }
+
+ /**
+ * The fallback key for an image that cannot be fingerprinted must be exact rather than a hash
+ * of the object, so two unfingerprintable images can never collapse into one zip entry. A
+ * per-document sequence is exact; anything derived from the object's own identity is not, which
+ * is what a second run over fresh objects catches.
+ */
+ @Test
+ void unfingerprintableImages_getExactPerDocumentFallbackKeys() throws Exception {
+ try (PDDocument doc = new PDDocument()) {
+ List<String> first = fallbackKeys(doc, 3);
+ List<String> second = fallbackKeys(doc, 3);
+
+ assertThat(first).doesNotHaveDuplicates().isEqualTo(second);
+ }
+ }
+
+ @Test
+ void unfingerprintableImage_isFirstOccurrenceOnlyOnce() throws Exception {
+ try (PDDocument doc = new PDDocument()) {
+ ImageFingerprints fingerprints = new ImageFingerprints();
+ PDImageXObject image = unfingerprintable(doc);
+
+ assertThat(fingerprints.isFirstOccurrence(image)).isTrue();
+ assertThat(fingerprints.isFirstOccurrence(image)).isFalse();
+ assertThat(fingerprints.isFirstOccurrence(unfingerprintable(doc))).isTrue();
+ }
+ }
+
+ private static List<String> fallbackKeys(PDDocument doc, int images) throws IOException {
+ ImageFingerprints fingerprints = new ImageFingerprints();
+ List<String> keys = new ArrayList<>();
+ for (int i = 0; i < images; i++) {
+ keys.add(fingerprints.keyFor(unfingerprintable(doc)));
+ }
+ return keys;
+ }
+
+ private static PDImageXObject unfingerprintable(PDDocument doc) throws IOException {
+ PDImageXObject image =
+ new PDImageXObject(
+ doc,
+ new ByteArrayInputStream(new byte[] {0x01, 0x02, 0x03, 0x04}),
+ COSName.FLATE_DECODE,
+ 4,
+ 1,
+ 8,
+ PDDeviceGray.INSTANCE);
+ image.getCOSObject().setItem(COSName.DECODE_PARMS, wideDictionary(5000));
+ return image;
+ }
+
+ private static PDImageXObject softMask(PDDocument doc) throws IOException {
+ byte[] mask = new byte[40 * 30];
+ java.util.Arrays.fill(mask, (byte) 0x40);
+ return new PDImageXObject(
+ doc,
+ new ByteArrayInputStream(mask),
+ COSName.FLATE_DECODE,
+ 40,
+ 30,
+ 8,
+ PDDeviceGray.INSTANCE);
+ }
+
+ @Test
+ void metadataOnlyDifference_sameKey() throws Exception {
+ try (PDDocument doc = new PDDocument()) {
+ BufferedImage img = solid(BufferedImage.TYPE_INT_RGB, new Color(10, 20, 30));
+ PDImageXObject a = JPEGFactory.createFromImage(doc, img);
+ PDImageXObject b = JPEGFactory.createFromImage(doc, img);
+ b.getCOSObject().setItem(COSName.METADATA, wideDictionary(8));
+ assertThat(key(a)).isEqualTo(key(b));
+ }
+ }
+
+ /**
+ * A chain of {@code levels} dictionaries in which every one of a node's {@code fanOut} entries
+ * points at the same child object, so a walk that forgets a node once it leaves it re-walks the
+ * child once per incoming edge.
+ */
+ private static COSObject sharedChild(int levels, int fanOut) {
+ COSObject node = new COSObject(new COSDictionary(), new COSObjectKey(levels + 1L, 0));
+ for (int level = levels; level >= 1; level--) {
+ COSDictionary dictionary = new COSDictionary();
+ for (int edge = 0; edge < fanOut; edge++) {
+ dictionary.setItem(COSName.getPDFName("Edge" + edge), node);
+ }
+ node = new COSObject(dictionary, new COSObjectKey(level, 0));
+ }
+ return node;
+ }
+
+ private static COSDictionary wideDictionary(int entries) {
+ COSDictionary dictionary = new COSDictionary();
+ for (int i = 0; i < entries; i++) {
+ dictionary.setInt(COSName.getPDFName("K" + i), i);
+ }
+ return dictionary;
+ }
+
+ private static COSArray indexed(byte[] palette) {
+ COSArray cs = new COSArray();
+ cs.add(COSName.INDEXED);
+ cs.add(COSName.DEVICERGB);
+ cs.add(COSInteger.get(1));
+ cs.add(new COSString(palette));
+ return cs;
+ }
+}