Example usage for javax.imageio ImageReader getDefaultReadParam

List of usage examples for javax.imageio ImageReader getDefaultReadParam

Introduction

In this page you can find the example usage for javax.imageio ImageReader getDefaultReadParam.

Prototype

public ImageReadParam getDefaultReadParam() 

Source Link

Document

Returns a default ImageReadParam object appropriate for this format.

Usage

From source file:org.apache.xmlgraphics.image.loader.impl.imageio.ImageLoaderImageIO.java

/** {@inheritDoc} */
public Image loadImage(ImageInfo info, Map hints, ImageSessionContext session)
        throws ImageException, IOException {
    RenderedImage imageData = null;
    IIOException firstException = null;

    IIOMetadata iiometa = (IIOMetadata) info.getCustomObjects().get(ImageIOUtil.IMAGEIO_METADATA);
    boolean ignoreMetadata = (iiometa != null);
    boolean providerIgnoresICC = false;

    Source src = session.needSource(info.getOriginalURI());
    ImageInputStream imgStream = ImageUtil.needImageInputStream(src);
    try {/*from  w  w w . j av  a 2s .  c  om*/
        Iterator iter = ImageIO.getImageReaders(imgStream);
        while (iter.hasNext()) {
            ImageReader reader = (ImageReader) iter.next();
            try {
                imgStream.mark();
                ImageReadParam param = reader.getDefaultReadParam();
                reader.setInput(imgStream, false, ignoreMetadata);
                final int pageIndex = ImageUtil.needPageIndexFromURI(info.getOriginalURI());
                try {
                    if (ImageFlavor.BUFFERED_IMAGE.equals(this.targetFlavor)) {
                        imageData = reader.read(pageIndex, param);
                    } else {
                        imageData = reader.read(pageIndex, param);
                        //imageData = reader.readAsRenderedImage(pageIndex, param);
                        //TODO Reenable the above when proper listeners are implemented
                        //to react to late pixel population (so the stream can be closed
                        //properly).
                    }
                    if (iiometa == null) {
                        iiometa = reader.getImageMetadata(pageIndex);
                    }
                    providerIgnoresICC = checkProviderIgnoresICC(reader.getOriginatingProvider());
                    break; //Quit early, we have the image
                } catch (IndexOutOfBoundsException indexe) {
                    throw new ImageException("Page does not exist. Invalid image index: " + pageIndex);
                } catch (IllegalArgumentException iae) {
                    //Some codecs like com.sun.imageio.plugins.wbmp.WBMPImageReader throw
                    //IllegalArgumentExceptions when they have trouble parsing the image.
                    throw new ImageException("Error loading image using ImageIO codec", iae);
                } catch (IIOException iioe) {
                    if (firstException == null) {
                        firstException = iioe;
                    } else {
                        log.debug("non-first error loading image: " + iioe.getMessage());
                    }
                }
                try {
                    //Try fallback for CMYK images
                    BufferedImage bi = getFallbackBufferedImage(reader, pageIndex, param);
                    imageData = bi;
                    firstException = null; //Clear exception after successful fallback attempt
                    break;
                } catch (IIOException iioe) {
                    //ignore
                }
                imgStream.reset();
            } finally {
                reader.dispose();
            }
        }
    } finally {
        ImageUtil.closeQuietly(src);
        //TODO Some codecs may do late reading.
    }
    if (firstException != null) {
        throw new ImageException("Error while loading image: " + firstException.getMessage(), firstException);
    }
    if (imageData == null) {
        throw new ImageException("No ImageIO ImageReader found .");
    }

    ColorModel cm = imageData.getColorModel();

    Color transparentColor = null;
    if (cm instanceof IndexColorModel) {
        //transparent color will be extracted later from the image
    } else {
        if (providerIgnoresICC && cm instanceof ComponentColorModel) {
            // Apply ICC Profile to Image by creating a new image with a new
            // color model.
            ICC_Profile iccProf = tryToExctractICCProfile(iiometa);
            if (iccProf != null) {
                ColorModel cm2 = new ComponentColorModel(new ICC_ColorSpace(iccProf), cm.hasAlpha(),
                        cm.isAlphaPremultiplied(), cm.getTransparency(), cm.getTransferType());
                WritableRaster wr = Raster.createWritableRaster(imageData.getSampleModel(), null);
                imageData.copyData(wr);
                BufferedImage bi = new BufferedImage(cm2, wr, cm2.isAlphaPremultiplied(), null);
                imageData = bi;
                cm = cm2;
            }
        }
        // ImageIOUtil.dumpMetadataToSystemOut(iiometa);
        // Retrieve the transparent color from the metadata
        if (iiometa != null && iiometa.isStandardMetadataFormatSupported()) {
            Element metanode = (Element) iiometa.getAsTree(IIOMetadataFormatImpl.standardMetadataFormatName);
            Element dim = ImageIOUtil.getChild(metanode, "Transparency");
            if (dim != null) {
                Element child;
                child = ImageIOUtil.getChild(dim, "TransparentColor");
                if (child != null) {
                    String value = child.getAttribute("value");
                    if (value == null || value.length() == 0) {
                        //ignore
                    } else if (cm.getNumColorComponents() == 1) {
                        int gray = Integer.parseInt(value);
                        transparentColor = new Color(gray, gray, gray);
                    } else {
                        StringTokenizer st = new StringTokenizer(value);
                        transparentColor = new Color(Integer.parseInt(st.nextToken()),
                                Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()));
                    }
                }
            }
        }
    }

    if (ImageFlavor.BUFFERED_IMAGE.equals(this.targetFlavor)) {
        return new ImageBuffered(info, (BufferedImage) imageData, transparentColor);
    } else {
        return new ImageRendered(info, imageData, transparentColor);
    }
}

From source file:org.carcv.core.model.file.FileCarImage.java

/**
 * Reads a rectangular region from an image in the inStream.
 *
 * @param inStream the InputStream from which to load the image fraction
 * @param rect specifies the rectangular region to load as the image
 * @throws IOException if an error during loading occurs
 *//*from   w ww .j  ava2  s .  c o  m*/
public void loadFragment(InputStream inStream, Rectangle rect) throws IOException {
    ImageInputStream imageStream = ImageIO.createImageInputStream(inStream);
    ImageReader reader = ImageIO.getImageReaders(imageStream).next();
    ImageReadParam param = reader.getDefaultReadParam();

    param.setSourceRegion(rect);
    reader.setInput(imageStream, true, true);

    this.image = reader.read(0, param);

    reader.dispose();
    imageStream.close();
}

From source file:org.dcm4che2.tool.dcm2jpg.Dcm2Jpg.java

public void convert(File src, File dest) throws IOException {
    Iterator<ImageReader> iter = ImageIO.getImageReadersByFormatName("DICOM");
    ImageReader reader = iter.next();
    DicomImageReadParam param = (DicomImageReadParam) reader.getDefaultReadParam();
    param.setWindowCenter(center);/*from  w w  w. j  a  va 2s .co  m*/
    param.setWindowWidth(width);
    param.setVoiLutFunction(vlutFct);
    param.setPresentationState(prState);
    param.setPValue2Gray(pval2gray);
    param.setAutoWindowing(autoWindowing);
    ImageInputStream iis = ImageIO.createImageInputStream(src);
    BufferedImage bi;
    try {
        reader.setInput(iis, false);
        bi = reader.read(frame - 1, param);
        if (bi == null) {
            System.out.println("\nError: " + src + " - couldn't read!");
            return;
        }
        if (imageWriterClassname == null) {
            encodeByJPEGEncoder(bi, dest);
        } else {
            encodeByImageIO(bi, dest);
        }
    } finally {
        CloseUtils.safeClose(iis);
    }
    System.out.print('.');
}

From source file:org.freecine.filmscan.ScanStrip.java

/**
 Load the scan strip image from disk/*  ww w  .j a v a  2  s.  c o m*/
 */
private void loadImage() {
    ImageReader reader;
    try {
        //        PlanarImage img = JAI.create( "fileload", fname );
        ImageInputStream istrm = new FileImageInputStream(file);
        reader = ImageIO.getImageReadersByFormatName("TIFF").next();
        reader.setInput(istrm);
        ImageReadParam param = reader.getDefaultReadParam();

        /*
         Set the color mode to linear sRGB as we don't have a better profile
         for the scanner/film available
         */
        ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_LINEAR_RGB);
        ImageLayout layout = new ImageLayout();
        ColorModel cm = new ComponentColorModel(cs, false, false, ColorModel.OPAQUE, DataBuffer.TYPE_USHORT);
        layout.setColorModel(cm);
        RenderingHints hints = new RenderingHints(JAI.KEY_IMAGE_LAYOUT, layout);
        stripImage = ImageReadDescriptor.create(istrm, 0, false, false, false, null, null, param, reader,
                hints);
        System.out.println("Color model " + stripImage.getColorModel());
        // BufferedImage inImg = reader.read( 0, param );            
    } catch (FileNotFoundException ex) {
        System.out.println(ex.getMessage());
        log.error("Strip file " + file + " not found", ex);
    } catch (IOException ex) {
        log.error("IO error reading strip " + file + ": ", ex);
    }
}

From source file:org.hippoecm.frontend.plugins.gallery.imageutil.ImageUtils.java

/**
 * Converts image raster data to a JPEG with RGB color space. Only images with color space CMYK and YCCK are
 * converted, other images are left untouched.
 *
 * Rationale: Java's ImageIO can't process 4-component images and Java2D can't apply AffineTransformOp either,
 * so we have to convert raster data to a JPG with RGB color space.
 *
 * The technique used in this method is due to Mark Stephens, and free for any use. See
 * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4799903 or
 * http://www.mail-archive.com/java2d-interest@capra.eng.sun.com/msg03247.html
 *
 * @param is the image data//from ww w.  j ava2  s .  c  o  m
 * @param colorModel the color model of the image
 * @return the RGB version of the supplied image
 */
public static InputStream convertToRGB(InputStream is, ColorModel colorModel)
        throws IOException, UnsupportedImageException {
    if (colorModel != ColorModel.CMYK && colorModel != ColorModel.YCCK) {
        return is;
    }

    // Get an ImageReader.
    ImageInputStream input = ImageIO.createImageInputStream(is);

    try {
        Iterator<ImageReader> readers = ImageIO.getImageReaders(input);
        if (readers == null || !readers.hasNext()) {
            throw new UnsupportedImageException("No ImageReaders found");
        }

        ImageReader reader = readers.next();
        reader.setInput(input);
        Raster raster = reader.readRaster(0, reader.getDefaultReadParam());

        int w = raster.getWidth();
        int h = raster.getHeight();
        byte[] rgb = new byte[w * h * 3];

        switch (colorModel) {
        case YCCK: {
            float[] Y = raster.getSamples(0, 0, w, h, 0, (float[]) null);
            float[] Cb = raster.getSamples(0, 0, w, h, 1, (float[]) null);
            float[] Cr = raster.getSamples(0, 0, w, h, 2, (float[]) null);
            float[] K = raster.getSamples(0, 0, w, h, 3, (float[]) null);

            for (int i = 0, imax = Y.length, base = 0; i < imax; i++, base += 3) {
                float k = 220 - K[i], y = 255 - Y[i], cb = 255 - Cb[i], cr = 255 - Cr[i];

                double val = y + 1.402 * (cr - 128) - k;
                val = (val - 128) * .65f + 128;
                rgb[base] = val < 0.0 ? (byte) 0 : val > 255.0 ? (byte) 0xff : (byte) (val + 0.5);

                val = y - 0.34414 * (cb - 128) - 0.71414 * (cr - 128) - k;
                val = (val - 128) * .65f + 128;
                rgb[base + 1] = val < 0.0 ? (byte) 0 : val > 255.0 ? (byte) 0xff : (byte) (val + 0.5);

                val = y + 1.772 * (cb - 128) - k;
                val = (val - 128) * .65f + 128;
                rgb[base + 2] = val < 0.0 ? (byte) 0 : val > 255.0 ? (byte) 0xff : (byte) (val + 0.5);
            }
            break;
        }
        case CMYK: {
            int[] C = raster.getSamples(0, 0, w, h, 0, (int[]) null);
            int[] M = raster.getSamples(0, 0, w, h, 1, (int[]) null);
            int[] Y = raster.getSamples(0, 0, w, h, 2, (int[]) null);
            int[] K = raster.getSamples(0, 0, w, h, 3, (int[]) null);

            for (int i = 0, imax = C.length, base = 0; i < imax; i++, base += 3) {
                int c = 255 - C[i];
                int m = 255 - M[i];
                int y = 255 - Y[i];
                int k = 255 - K[i];
                float kk = k / 255f;

                rgb[base] = (byte) (255 - Math.min(255f, c * kk + k));
                rgb[base + 1] = (byte) (255 - Math.min(255f, m * kk + k));
                rgb[base + 2] = (byte) (255 - Math.min(255f, y * kk + k));
            }
            break;
        }
        }

        // from other image types we know InterleavedRaster's can be
        // manipulated by AffineTransformOp, so create one of those.
        raster = Raster.createInterleavedRaster(new DataBufferByte(rgb, rgb.length), w, h, w * 3, 3,
                new int[] { 0, 1, 2 }, null);

        ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
        java.awt.image.ColorModel cm = new ComponentColorModel(cs, false, true, Transparency.OPAQUE,
                DataBuffer.TYPE_BYTE);
        BufferedImage convertedImage = new BufferedImage(cm, (WritableRaster) raster, true, null);

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(convertedImage, "jpg", os);

        return new ByteArrayInputStream(os.toByteArray());
    } finally {
        IOUtils.closeQuietly(is);
        if (input != null) {
            input.close();
        }
    }
}

From source file:org.jimcat.services.imagemanager.ImageUtil.java

/**
 * use this methode to load an image from a given byte array
 * //from   w  w w.j a  v a2  s.co  m
 * @param data -
 *            the byte array containing an encoded image
 * @param quality
 *            the rendering quality
 * @return - a Buffered Image containing image. Its size is limited by
 *         SOURCE_BOUNDING_BOX constant
 * @throws IOException -
 *             if something goes wrong
 */
public static BufferedImage loadImage(byte[] data, ImageQuality quality) throws IOException {

    // read first element
    ImageReader reader = getReaderForImage(data);

    // get image dimension and calculate resulting image size
    int width = reader.getWidth(0);
    int height = reader.getHeight(0);
    Dimension size = getScaledDimension(width, height, SOURCE_BOUNDING_BOX, false);

    // performe read
    BufferedImage bi = null;
    try {
        if (USE_TILES) {
            // if image is smaller than a tile
            if (width <= IMAGE_TILE_SIZE.width && height <= IMAGE_TILE_SIZE.height) {
                bi = reader.read(0);
            } else {
                // prepaire reader
                ImageReadParam param = reader.getDefaultReadParam();

                // so image is bigger than a tile
                // a) check if reader supports source scaling
                if (param.canSetSourceRenderSize()) {
                    // fine => do it so
                    param.setSourceRenderSize(size);
                    bi = reader.read(0, param);
                } else {
                    // so, scaling has to be done by hand
                    bi = loadImageWithTiles(reader, size, quality);
                }
            }
        } else {
            bi = loadImageWithSubSampling(reader, size, quality);
        }
    } finally {
        reader.dispose();
    }
    return bi;
}

From source file:org.jimcat.services.imagemanager.ImageUtil.java

/**
 * this methode will load given image using tiles (saving memory)
 * //w  w w  .jav  a2 s.  c om
 * this strategie is spliting the original image up into smaller parts
 * called tiles. Those tiles are downscaled one by one using given quality.
 * This results int probably best possible quality but may cost a lot of
 * time.
 * 
 * @param reader -
 *            the reader to load image from
 * @param size -
 *            the resulting image size
 * @param quality -
 *            the quality used for necessary rendering
 * @return the image as buffered image
 * @throws IOException
 */
@SuppressWarnings("unused")
private static BufferedImage loadImageWithTiles(ImageReader reader, Dimension size, ImageQuality quality)
        throws IOException {

    // the image buffer used to load tiles
    ImageTypeSpecifier imageSpec = reader.getImageTypes(0).next();
    BufferedImage tile = imageSpec.createBufferedImage(IMAGE_TILE_SIZE.width, IMAGE_TILE_SIZE.height);

    // the image the result is rendered into
    BufferedImage result = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = result.createGraphics();
    g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, quality.getHint());

    // prepaire image reader parameter
    ImageReadParam param = reader.getDefaultReadParam();
    param.setDestination(tile);

    // count tiles
    int width = reader.getWidth(0);
    int height = reader.getHeight(0);
    int numX = (int) Math.ceil(width / (float) IMAGE_TILE_SIZE.width);
    int numY = (int) Math.ceil(height / (float) IMAGE_TILE_SIZE.height);

    float aspectX = (float) IMAGE_TILE_SIZE.width / width;
    float aspectY = (float) IMAGE_TILE_SIZE.height / height;

    // target tile dimension
    int targetTileWidth = (int) (size.width * aspectX);
    int targetTileHeight = (int) (size.height * aspectY);

    // load tiles
    Rectangle sourceRegion = new Rectangle();
    Rectangle targetRegion = new Rectangle();
    for (int i = 0; i < numX; i++) {
        // line increment
        sourceRegion.x = i * IMAGE_TILE_SIZE.width;
        sourceRegion.width = Math.min(IMAGE_TILE_SIZE.width, width - sourceRegion.x);
        targetRegion.x = i * targetTileWidth;
        targetRegion.width = Math.min(targetTileWidth, size.width - targetRegion.x);
        for (int j = 0; j < numY; j++) {
            // row increment
            sourceRegion.y = j * IMAGE_TILE_SIZE.height;
            sourceRegion.height = Math.min(IMAGE_TILE_SIZE.height, height - sourceRegion.y);
            targetRegion.y = j * targetTileHeight;
            targetRegion.height = Math.min(targetTileHeight, size.height - targetRegion.y);

            // performe read
            param.setSourceRegion(sourceRegion);
            reader.read(0, param);

            // insert into resulting image
            int dx1 = targetRegion.x;
            int dx2 = targetRegion.x + targetRegion.width;
            int dy1 = targetRegion.y;
            int dy2 = targetRegion.y + targetRegion.height;

            g.drawImage(tile, dx1, dy1, dx2, dy2, 0, 0, sourceRegion.width, sourceRegion.height, null);
        }
    }

    // finish drawing
    g.dispose();

    // return result
    return result;
}

From source file:org.jimcat.services.imagemanager.ImageUtil.java

/**
 * this methode will load given image using a subsample rate
 * //from  w  ww .  jav a  2 s.  com
 * this strategie is just reading a subset of images lines ans rowes to
 * reduce memory usage and cpu time.
 * 
 * @param reader -
 *            the reader to load image from
 * @param size -
 *            the resulting image size
 * @param quality -
 *            the quality used for necessary rendering
 * @return the image as buffered image
 * @throws IOException
 */
private static BufferedImage loadImageWithSubSampling(ImageReader reader, Dimension size, ImageQuality quality)
        throws IOException {

    // prepaire image reader parameter
    ImageReadParam param = reader.getDefaultReadParam();

    // calculate subsampling values
    int width = reader.getWidth(0);
    int height = reader.getHeight(0);
    int rateX = width / size.width;
    int rateY = height / size.height;
    param.setSourceSubsampling(rateX, rateY, 0, 0);

    // load image with subsamples
    BufferedImage img = reader.read(0, param);

    // scale to final size
    BufferedImage result = getScaledInstance(img, size, quality);

    // return result
    return result;
}

From source file:org.medici.bia.controller.manuscriptviewer.IIPImageServerController.java

/**
 * /*from ww w . j  a v a 2 s .c  om*/
 * @param fileName
 * @param pageImage
 * @param tileNumber
 * @param xCoordinate
 * @param yCoordinate
 * @param httpServletResponse
 */
@SuppressWarnings("unused")
private void generateTiledImage(String fileName, Integer pageImage, Integer tileNumber, Integer xCoordinate,
        Integer yCoordinate, HttpServletResponse httpServletResponse) {
    File imageFile = new File(
            ApplicationPropertyManager.getApplicationProperty("iipimage.image.path") + fileName);
    Integer imageWidth = new Integer(0);
    Integer imageHeight = new Integer(0);
    Integer tileWidth = new Integer(0);
    Integer tileHeight = new Integer(0);
    Integer resolutionNumber = new Integer(0);
    Integer convertedPageImage = new Integer(0);

    ImageInputStream imageInputStream = null;
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    InputStream inputStream = null;

    try {
        if (imageFile.canRead()) {
            // Reading complete tiff information
            imageInputStream = ImageIO.createImageInputStream(imageFile);
        } else {
            logger.error("File " + imageFile.toString() + " is not present on filesystem. ");
            imageFile = new File(ApplicationPropertyManager.getApplicationProperty("iipimage.image.path")
                    + ApplicationPropertyManager.getApplicationProperty("iipimage.image.notavailable"));
            if (imageFile.canRead()) {
                // Reading complete tiff information
                imageInputStream = ImageIO.createImageInputStream(imageFile);
            } else {
                logger.error("File " + imageFile.toString() + " is not present on filesystem. ");
            }
        }

        if (imageInputStream != null) {
            Iterator<ImageReader> readers = ImageIO.getImageReaders(imageInputStream);
            if (readers.hasNext()) {
                ImageReader reader = readers.next();
                reader.setInput(imageInputStream, false, true);
                tileWidth = reader.getTileWidth(0);
                tileHeight = reader.getTileHeight(0);
                imageWidth = reader.getWidth(0);
                imageHeight = reader.getHeight(0);
                // Last level is not readable, I don't know why but i remove
                // this
                resolutionNumber = reader.getNumImages(true) - 1;
                // Calculate of image position, final -1 is beacause index
                // start from 0 and not from 1
                convertedPageImage = resolutionNumber - pageImage;
                // We read our specific tile
                ImageReadParam param = reader.getDefaultReadParam();
                param.setSourceRegion(
                        new Rectangle(new Point(xCoordinate * tileWidth, yCoordinate * tileHeight),
                                new Dimension(tileWidth, tileHeight)));
                BufferedImage subImage = reader.read(convertedPageImage, param);
                // preparing image for output
                ImageIO.write(subImage, "jpeg", byteArrayOutputStream);
                inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
                // writing image to output
                httpServletResponse.setContentType("image/jpeg");
                IOUtils.copy(inputStream, httpServletResponse.getOutputStream());

                // Flushing request
                httpServletResponse.getOutputStream().flush();
            }
        } else {
            logger.error("File " + imageFile.toString() + " is not present on filesystem.");
        }
    } catch (IOException ioException) {
        logger.error(ioException);
    } finally {
        try {
            if (inputStream != null) {
                inputStream.close();
            }
        } catch (IOException ioException) {
        }
        try {
            if (byteArrayOutputStream != null) {
                byteArrayOutputStream.close();
            }
        } catch (IOException ioException) {
        }
        try {
            if (imageInputStream != null) {
                imageInputStream.close();
            }
        } catch (IOException ioException) {
        }
    }
}

From source file:org.olat.core.commons.services.image.spi.ImageHelperImpl.java

private static SizeAndBufferedImage calcScaledSize(ImageInputStream stream, String suffix, int maxWidth,
        int maxHeight, boolean fill) {
    Iterator<ImageReader> iter = ImageIO.getImageReadersBySuffix(suffix);
    if (iter.hasNext()) {
        ImageReader reader = iter.next();
        try {/* w  w w.  j  av  a2 s  . co  m*/
            reader.setInput(stream, true, true);
            int width = reader.getWidth(reader.getMinIndex());
            int height = reader.getHeight(reader.getMinIndex());
            Size size = new Size(width, height, false);
            Size scaledSize = computeScaledSize(width, height, maxWidth, maxHeight, fill);
            SizeAndBufferedImage all = new SizeAndBufferedImage(size, scaledSize);

            int readerMinIndex = reader.getMinIndex();
            ImageReadParam param = reader.getDefaultReadParam();
            Iterator<ImageTypeSpecifier> imageTypes = reader.getImageTypes(0);
            while (imageTypes.hasNext()) {
                try {
                    ImageTypeSpecifier imageTypeSpecifier = imageTypes.next();
                    int bufferedImageType = imageTypeSpecifier.getBufferedImageType();
                    if (bufferedImageType == BufferedImage.TYPE_BYTE_GRAY) {
                        param.setDestinationType(imageTypeSpecifier);
                    }

                    double memoryKB = (width * height * 4) / 1024d;
                    if (memoryKB > 2000) {// check limit at 20MB
                        double free = Runtime.getRuntime().freeMemory() / 1024d;
                        if (free > memoryKB) {
                            all.setImage(reader.read(readerMinIndex, param));
                        } else {
                            // make sub sampling to save memory
                            int ratio = (int) Math.round(Math.sqrt(memoryKB / free));
                            param.setSourceSubsampling(ratio, ratio, 0, 0);
                            all.setImage(reader.read(readerMinIndex, param));
                        }
                    } else {
                        all.setImage(reader.read(readerMinIndex, param));
                    }
                    return all;
                } catch (IllegalArgumentException e) {
                    log.warn(e.getMessage(), e);
                }
            }
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } finally {
            reader.dispose();
        }
    } else {
        log.error("No reader found for given format: " + suffix, null);
    }
    return null;
}