Skip to content

optimize JPEGFactory methods - #497

Open
valerybokov wants to merge 1 commit into
apache:trunkfrom
valerybokov:optimize-JPEGFactory-methods
Open

optimize JPEGFactory methods#497
valerybokov wants to merge 1 commit into
apache:trunkfrom
valerybokov:optimize-JPEGFactory-methods

Conversation

@valerybokov

Copy link
Copy Markdown

The current version of the JPEGFactory.createFromByteArray method always creates a ByteArrayInputStream instance to read the image dimensions, and then creates a PDImageXObject instance. If we use the JPEGFactory.createFromStream method, we have a stream instance and create a new array. This is inefficient. We can work with streams and avoid duplicating memory (the InputStream from createFromStream can also be a ByteArrayInputStream).
I thought the InputStream.markSupported method should be used, and I found this information. The BufferedInputStream.reset() method can throw an exception only in a pathological extreme case: if, after mark(), more bytes were read than fit in the Java array (~2 GB). This isn't a drawback specific to BufferedInputStream—it's a fundamental limitation on storing arbitrary, rewindable data in memory, and it affects all approaches, including the original code before the refactoring (stream.readAllBytes()), which also resulted in an error (out of memory or exceeding array size limits) when handling multi-gigabyte input data. Therefore, BufferedInputStream is no worse than the alternative—it's just as good for realistic input data, with the same theoretical limit as everything else.
If this isn't acceptable, I can rewrite it using the markSupported method.
An additional benefit: the PDImageXObject.createFromFileByContent method now uses BufferedInputStream via the JPEGFactory.createFromStream method.

{
// copy stream
ByteArrayInputStream byteStream = new ByteArrayInputStream(byteArray);
if (!(stream instanceof ByteArrayInputStream) && !(stream instanceof BufferedInputStream))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if (!(stream instanceof ByteArrayInputStream) && !(stream instanceof BufferedInputStream))
if (!stream.markSupported())

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants