Example usage for javax.imageio ImageReader getHeight

List of usage examples for javax.imageio ImageReader getHeight

Introduction

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

Prototype

public abstract int getHeight(int imageIndex) throws IOException;

Source Link

Document

Returns the height in pixels of the given image within the input source.

Usage

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 .ja  v  a  2 s  .  c  o  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)
 * /*from   ww w  .jav a2  s  .co  m*/
 * 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   www  .  j a  v a2s  . c om*/
 * 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.jimcat.services.imagemanager.ImageUtil.java

/**
 * get the dimension of the image stored inside the given array
 * //from w w w  .j  a v a 2  s . co m
 * @param image
 * @return the image dimension
 * @throws IOException
 */
private static Dimension getImageDimension(byte image[]) throws IOException {
    ImageReader reader = getReaderForImage(image);
    return new Dimension(reader.getWidth(0), reader.getHeight(0));
}

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

/**
 * This method return image and tile information.
 * /*from   w w  w. ja va  2 s  .c  o m*/
 * EXAMPLE OUTPUT : IIP:1.0 Max-size:1832 2448 Tile-size:128 128
 * Resolution-number:6
 * 
 * @param httpServletRequest
 * @param response
 * 
 */
private void generateInformationsTiledImage(HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse) {
    File imageFile = new File(ApplicationPropertyManager.getApplicationProperty("iipimage.image.path")
            + httpServletRequest.getParameter("FIF"));
    ImageInputStream imageInputStream = null;
    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);

    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);
            }
        }
    } catch (IOException ioException) {
        logger.debug(ioException);
    } finally {
        try {
            if (imageInputStream != null) {
                imageInputStream.close();
            }
        } catch (IOException ioException) {
        }

        try {
            httpServletResponse.setContentType("text/plain");
            ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
            servletOutputStream.println("IIP:1.0");
            servletOutputStream.println("Max-size:" + imageWidth + " " + imageHeight);
            servletOutputStream.println("Tile-size:" + tileWidth + " " + tileHeight);
            servletOutputStream.println("Resolution-number:" + resolutionNumber);
            servletOutputStream.println("");
            httpServletResponse.getOutputStream().flush();
        } catch (IOException ioException) {
            logger.error(ioException);
        }
    }
}

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

/**
 * //from www .  j  a  v a  2s.c o m
 * @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.AbstractImageHelper.java

private Size getImageSize(VFSLeaf media, String suffix) {
    Size result = null;//from   w  w  w .  java2s  . co  m
    Iterator<ImageReader> iter = ImageIO.getImageReadersBySuffix(suffix);
    if (iter.hasNext()) {
        ImageInputStream stream = null;
        InputStream mediaStream = null;
        ImageReader reader = iter.next();
        try {
            mediaStream = media.getInputStream();
            if (mediaStream != null) {
                stream = new MemoryCacheImageInputStream(mediaStream);
                reader.setInput(stream);
                int readerMinIndex = reader.getMinIndex();
                int width = reader.getWidth(readerMinIndex);
                int height = reader.getHeight(readerMinIndex);
                result = new Size(width, height, 0, 0, false);
            }
        } catch (IOException e) {
            log.error(e.getMessage());
        } finally {
            IOUtils.closeQuietly(stream);
            IOUtils.closeQuietly(mediaStream);
            reader.dispose();
        }
    } else {
        log.error("No reader found for given format: " + suffix);
    }
    return result;
}

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  a  2s.c  o 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;
}

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

private static SizeAndBufferedImage getImage(ImageInputStream stream, String suffix) {
    Iterator<ImageReader> iter = ImageIO.getImageReadersBySuffix(suffix);
    if (iter.hasNext()) {
        ImageReader reader = iter.next();
        try {//  www.  j av  a  2 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);
            SizeAndBufferedImage all = new SizeAndBufferedImage(size, null);

            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);
                    }
                    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;
}

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 w w . j  a v  a 2s . 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;
}