Skip to content

Commit

Permalink
fix: avoid OutOfMemoryError when computing image size
Browse files Browse the repository at this point in the history
Use a `FileImageInputStream` instead of a `BufferedImage`.
  • Loading branch information
DocJM authored May 1, 2020
1 parent 0b346fd commit 929806b
Showing 1 changed file with 10 additions and 15 deletions.
25 changes: 10 additions & 15 deletions src/main/java/com/adobe/epubcheck/bitmap/BitmapChecker.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@

package com.adobe.epubcheck.bitmap;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
Expand All @@ -31,6 +30,7 @@

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.FileImageInputStream;
import javax.imageio.stream.ImageInputStream;

import com.adobe.epubcheck.api.EPUBLocation;
Expand Down Expand Up @@ -119,6 +119,7 @@ public ImageHeuristics getImageSizes(String imgFileName) throws
tempFile = getImageFile(ocf, imgFileName);
String formatFromInputStream = null;
String formatFromSuffix = null;
ImageReader reader = null;
ImageInputStream imageInputStream = ImageIO.createImageInputStream(tempFile);
Iterator<ImageReader> imageReaderIteratorFromInputStream = ImageIO.getImageReaders(imageInputStream);
while (imageReaderIteratorFromInputStream.hasNext()) {
Expand All @@ -127,7 +128,7 @@ public ImageHeuristics getImageSizes(String imgFileName) throws

Iterator<ImageReader> imageReaderIteratorFromSuffix = ImageIO.getImageReadersBySuffix(suffix);
while (imageReaderIteratorFromSuffix.hasNext()) {
ImageReader reader = imageReaderIteratorFromSuffix.next();
reader = imageReaderIteratorFromSuffix.next();
formatFromSuffix = reader.getFormatName();

if (formatFromSuffix != null && formatFromSuffix.equals(formatFromInputStream)) break;
Expand All @@ -138,20 +139,14 @@ public ImageHeuristics getImageSizes(String imgFileName) throws



if (formatFromSuffix != null && formatFromSuffix.equals(formatFromInputStream)) {
if (formatFromSuffix != null && formatFromSuffix.equals(formatFromInputStream)) {
// file format and file extension matches; read image file

try {
BufferedImage image = ImageIO.read(tempFile);
if (image == null) {
report.message(MessageId.PKG_021, EPUBLocation.create(imgFileName));
return null;

} else {
int width = image.getWidth();
int height = image.getHeight();
return new ImageHeuristics(width, height, tempFile.length());
}

try (ImageInputStream stream = new FileImageInputStream(tempFile)) {
reader.setInput(stream);
int width = reader.getWidth(reader.getMinIndex());
int height = reader.getHeight(reader.getMinIndex());
return new ImageHeuristics(width, height, tempFile.length());
}
catch (IOException e)
{
Expand Down

0 comments on commit 929806b

Please sign in to comment.