Example usage for javax.imageio ImageReader dispose

List of usage examples for javax.imageio ImageReader dispose

Introduction

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

Prototype

public void dispose() 

Source Link

Document

Allows any resources held by this object to be released.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    ImageInputStream imageStream = ImageIO.createImageInputStream(new URL("").openStream());
    Iterator<ImageReader> readers = ImageIO.getImageReaders(imageStream);
    ImageReader reader = null;
    if (!readers.hasNext()) {
        imageStream.close();//from w  ww  . j a va 2  s .c  o m
        return;
    } else {
        reader = readers.next();
    }
    String formatName = reader.getFormatName();
    if (!formatName.equalsIgnoreCase("jpeg") && !formatName.equalsIgnoreCase("png")
            && !formatName.equalsIgnoreCase("gif")) {
        imageStream.close();
        return;
    }
    reader.setInput(imageStream, true, true);
    BufferedImage theImage = reader.read(0);
    reader.dispose();
    imageStream.close();
}

From source file:Main.java

public static BufferedImage readFragment(InputStream stream, Rectangle rect) throws IOException {
    ImageInputStream imageStream = ImageIO.createImageInputStream(stream);
    ImageReader reader = ImageIO.getImageReaders(imageStream).next();
    ImageReadParam param = reader.getDefaultReadParam();

    param.setSourceRegion(rect);//from  w  w  w  .  j  av  a 2  s  . c  o m
    reader.setInput(imageStream, true, true);
    BufferedImage image = reader.read(0, param);

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

    return image;
}

From source file:com.alibaba.simpleimage.util.ImageUtils.java

public static void closeQuietly(ImageReader reader) {
    if (reader != null) {
        try {//from  ww w  .  j  av a2 s .  c o  m
            reader.dispose();
        } catch (Exception igonre) {

        }
    }
}

From source file:at.gv.egiz.pdfas.common.utils.ImageUtils.java

public static Dimension getImageDimensions(InputStream is) throws IOException {
    ImageInputStream in = ImageIO.createImageInputStream(is);
    try {//from  w  ww. j a  v  a2 s. c  om
        final Iterator<ImageReader> readers = ImageIO.getImageReaders(in);
        if (readers.hasNext()) {
            ImageReader reader = readers.next();
            try {
                reader.setInput(in);
                return new Dimension(reader.getWidth(0), reader.getHeight(0));
            } finally {
                reader.dispose();
            }
        }
        throw new IOException("Failed to read Image file");
    } finally {
        if (in != null)
            in.close();
    }
}

From source file:se.trixon.almond.GraphicsHelper.java

public static Dimension getImgageDimension(File imageFile) throws IOException {
    ImageInputStream inputStream = ImageIO.createImageInputStream(imageFile);

    try {/*from  w ww  .j  a  va  2s.co  m*/
        final Iterator<ImageReader> imageReaders = ImageIO.getImageReaders(inputStream);
        if (imageReaders.hasNext()) {
            ImageReader imageReader = imageReaders.next();
            try {
                imageReader.setInput(inputStream);
                return new Dimension(imageReader.getWidth(0), imageReader.getHeight(0));
            } finally {
                imageReader.dispose();
            }
        }
    } finally {
        if (inputStream != null) {
            inputStream.close();
        }
    }

    return null;
}

From source file:de.javagl.jgltf.model.io.GltfUtils.java

/**
 * Tries to detect the format of the given image data, and return the
 * corresponding string of the <code>"image/..."</code> MIME type.
 * This may, for example, be <code>"png"</code> or <code>"gif"</code>
 * or <code>"jpeg"</code> (**not** <code>"jpg"</code>!)
 *  //from w  ww  .jav a  2 s .c  o m
 * @param imageData The image data
 * @return The image format string
 * @throws IOException If the image format can not be detected
 */
private static String guessImageMimeTypeString(ByteBuffer imageData) throws IOException {
    ImageReader imageReader = null;
    try {
        imageReader = findImageReader(imageData);
        return imageReader.getFormatName();
    } finally {
        if (imageReader != null) {
            imageReader.dispose();
        }
    }

}

From source file:nl.b3p.viewer.print.PrintInfo.java

/**
 * Load image dimensions, ideally without decoding the entire image.
 *//*from ww w  .j av  a2 s  .  c om*/
private static Dimension getImageDimension(InputStream image) throws IOException {
    // http://stackoverflow.com/questions/1559253/java-imageio-getting-image-dimension-without-reading-the-entire-file

    ImageInputStream in = ImageIO.createImageInputStream(image);
    try {
        final Iterator<ImageReader> readers = ImageIO.getImageReaders(in);
        if (readers.hasNext()) {
            ImageReader reader = readers.next();
            try {
                reader.setInput(in);
                return new Dimension(reader.getWidth(0), reader.getHeight(0));
            } finally {
                reader.dispose();
            }
        }
    } finally {
        if (in != null) {
            in.close();
        }
    }
    return null;
}

From source file:org.onehippo.forge.gallerymagick.core.command.ScalrProcessorUtils.java

/**
 * Detects the {@code sourceFile} and returns the size dimension from it.
 * @param sourceFile source image file//from   w ww.  java 2  s. c  o  m
 * @return Detects the {@code sourceFile} and returns the size dimension from it
 * @throws IOException if IO exception occurs
 */
public static ImageDimension identifyDimension(File sourceFile) throws IOException {
    ImageDimension dimension = null;
    String extension = FilenameUtils.getExtension(sourceFile.getName());
    Iterator<ImageReader> it = ImageIO.getImageReadersBySuffix(extension);

    if (!it.hasNext()) {
        throw new IllegalArgumentException("Unsupported file name extension: " + sourceFile);
    }

    ImageReader reader = null;

    try {
        reader = getImageReader(sourceFile);
        int width = reader.getWidth(reader.getMinIndex());
        int height = reader.getHeight(reader.getMinIndex());
        dimension = ImageDimension.from(width, height);
    } finally {
        if (reader != null) {
            reader.dispose();
        }
    }

    return dimension;
}

From source file:it.geosolutions.geobatch.geotiff.retile.GeotiffRetilerAction.java

/**
 * @deprecated replaced by {@link #GeoTiffRetilerUtils.reTile(...)}
 *///from www  . j  a v  a2 s  .c  om
@Deprecated
public static void reTile(File inFile, File tiledTiffFile, double compressionRatio, String compressionType,
        int tileW, int tileH, boolean forceBigTiff) throws IOException {
    //
    // look for a valid file that we can read
    //

    AbstractGridFormat format = null;
    AbstractGridCoverage2DReader reader = null;
    GridCoverage2D inCoverage = null;
    AbstractGridCoverageWriter writer = null;
    final Hints hints = new Hints(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, Boolean.TRUE);

    // getting a format for the given input
    format = (AbstractGridFormat) GridFormatFinder.findFormat(inFile, hints);
    if (format == null || (format instanceof UnknownFormat)) {
        throw new IllegalArgumentException("Unable to find the GridFormat for the provided file: " + inFile);
    }

    try {
        //
        // ACQUIRING A READER
        //
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("Acquiring a reader for the provided file...");
        }

        // can throw UnsupportedOperationsException
        reader = (AbstractGridCoverage2DReader) format.getReader(inFile, hints);

        if (reader == null) {
            final IOException ioe = new IOException("Unable to find a reader for the provided file: " + inFile);
            throw ioe;
        }

        //
        // ACQUIRING A COVERAGE
        //
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("Acquiring a coverage provided file...");
        }
        inCoverage = (GridCoverage2D) reader.read(null);
        if (inCoverage == null) {
            final IOException ioe = new IOException("inCoverage == null");
            throw ioe;
        }

        //
        // PREPARING A WRITE
        //
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("Writing down the file in the decoded directory...");
        }

        final GeoTiffFormat wformat = new GeoTiffFormat();
        final GeoTiffWriteParams wp = new GeoTiffWriteParams();
        if (!Double.isNaN(compressionRatio) && compressionType != null) {
            wp.setCompressionMode(GeoTiffWriteParams.MODE_EXPLICIT);
            wp.setCompressionType(compressionType);
            wp.setCompressionQuality((float) compressionRatio);
        }
        wp.setForceToBigTIFF(forceBigTiff);
        wp.setTilingMode(GeoToolsWriteParams.MODE_EXPLICIT);
        wp.setTiling(tileW, tileH);
        final ParameterValueGroup wparams = wformat.getWriteParameters();
        wparams.parameter(AbstractGridFormat.GEOTOOLS_WRITE_PARAMS.getName().toString()).setValue(wp);

        //
        // ACQUIRING A WRITER AND PERFORMING A WRITE
        //
        writer = (AbstractGridCoverageWriter) new GeoTiffWriter(tiledTiffFile);
        writer.write(inCoverage,
                (GeneralParameterValue[]) wparams.values().toArray(new GeneralParameterValue[1]));

    } finally {
        //
        // PERFORMING FINAL CLEAN UP AFTER THE WRITE PROCESS
        //
        if (reader != null) {
            try {
                reader.dispose();
            } catch (Exception e) {
                if (LOGGER.isWarnEnabled())
                    LOGGER.warn(e.getLocalizedMessage(), e);
            }

        }

        if (writer != null) {
            try {
                writer.dispose();
            } catch (Exception e) {
                if (LOGGER.isWarnEnabled())
                    LOGGER.warn(e.getLocalizedMessage(), e);
            }

        }

        if (inCoverage != null) {
            final RenderedImage initImage = inCoverage.getRenderedImage();
            ImageReader r = (ImageReader) initImage.getProperty(ImageReadDescriptor.PROPERTY_NAME_IMAGE_READER);
            try {
                r.dispose();
            } catch (Exception e) {
                if (LOGGER.isWarnEnabled())
                    LOGGER.warn("GeotiffRetiler::reTile(): " + e.getLocalizedMessage(), e);
            }

            // dispose
            ImageUtilities.disposePlanarImageChain(PlanarImage.wrapRenderedImage(initImage));

        }
    }

}

From source file:it.geosolutions.geobatch.geotiff.retile.GeotiffRetiler.java

public static void reTile(File inFile, File tiledTiffFile, double compressionRatio, String compressionType,
        int tileW, int tileH, boolean forceBigTiff) throws IOException {
    ////from   w  ww . j a v  a2s.c o m
    // look for a valid file that we can read
    //

    AbstractGridFormat format = null;
    AbstractGridCoverage2DReader reader = null;
    GridCoverage2D inCoverage = null;
    AbstractGridCoverageWriter writer = null;
    final Hints hints = new Hints(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, Boolean.TRUE);

    // getting a format for the given input
    format = (AbstractGridFormat) GridFormatFinder.findFormat(inFile, hints);
    if (format == null || (format instanceof UnknownFormat)) {
        throw new IllegalArgumentException("Unable to find the GridFormat for the provided file: " + inFile);
    }

    try {
        //
        // ACQUIRING A READER
        //
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("Acquiring a reader for the provided file...");
        }

        // can throw UnsupportedOperationsException
        reader = (AbstractGridCoverage2DReader) format.getReader(inFile, hints);

        if (reader == null) {
            final IOException ioe = new IOException("Unable to find a reader for the provided file: " + inFile);
            throw ioe;
        }

        //
        // ACQUIRING A COVERAGE
        //
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("Acquiring a coverage provided file...");
        }
        inCoverage = (GridCoverage2D) reader.read(null);
        if (inCoverage == null) {
            final IOException ioe = new IOException("inCoverage == null");
            throw ioe;
        }

        //
        // PREPARING A WRITE
        //
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("Writing down the file in the decoded directory...");
        }

        final GeoTiffFormat wformat = new GeoTiffFormat();
        final GeoTiffWriteParams wp = new GeoTiffWriteParams();
        if (!Double.isNaN(compressionRatio) && compressionType != null) {
            wp.setCompressionMode(GeoTiffWriteParams.MODE_EXPLICIT);
            wp.setCompressionType(compressionType);
            wp.setCompressionQuality((float) compressionRatio);
        }
        wp.setForceToBigTIFF(forceBigTiff);
        wp.setTilingMode(GeoToolsWriteParams.MODE_EXPLICIT);
        wp.setTiling(tileW, tileH);
        final ParameterValueGroup wparams = wformat.getWriteParameters();
        wparams.parameter(AbstractGridFormat.GEOTOOLS_WRITE_PARAMS.getName().toString()).setValue(wp);

        //
        // ACQUIRING A WRITER AND PERFORMING A WRITE
        //
        writer = (AbstractGridCoverageWriter) new GeoTiffWriter(tiledTiffFile);
        writer.write(inCoverage,
                (GeneralParameterValue[]) wparams.values().toArray(new GeneralParameterValue[1]));

    } finally {
        //
        // PERFORMING FINAL CLEAN UP AFTER THE WRITE PROCESS
        //
        if (reader != null) {
            try {
                reader.dispose();
            } catch (Exception e) {
                if (LOGGER.isWarnEnabled())
                    LOGGER.warn(e.getLocalizedMessage(), e);
            }

        }

        if (writer != null) {
            try {
                writer.dispose();
            } catch (Exception e) {
                if (LOGGER.isWarnEnabled())
                    LOGGER.warn(e.getLocalizedMessage(), e);
            }

        }

        if (inCoverage != null) {
            final RenderedImage initImage = inCoverage.getRenderedImage();
            ImageReader r = (ImageReader) initImage.getProperty(ImageReadDescriptor.PROPERTY_NAME_IMAGE_READER);
            try {
                r.dispose();
            } catch (Exception e) {
                if (LOGGER.isWarnEnabled())
                    LOGGER.warn("GeotiffRetiler::reTile(): " + e.getLocalizedMessage(), e);
            }

            // dispose
            ImageUtilities.disposePlanarImageChain(PlanarImage.wrapRenderedImage(initImage));

        }
    }

}