Example usage for javax.imageio ImageReader getNumImages

List of usage examples for javax.imageio ImageReader getNumImages

Introduction

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

Prototype

public abstract int getNumImages(boolean allowSearch) throws IOException;

Source Link

Document

Returns the number of images, not including thumbnails, available from the current input source.

Usage

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

/**
 * This method return image and tile information.
 * //from ww  w .j  a  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 w w  w .j a  v  a  2s.co 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.medici.bia.controller.manuscriptviewer.IIPImageServerController.java

/**
 * //from  w  ww  . j a v  a 2s  . c  om
 * @param imageName
 * @param thumbnailWidth
 * @param thumbnailFormat
 * @param response
 */
private void generateThumbnailImage(String imageName, Double thumbnailWidth, Integer imageQuality,
        String thumbnailFormat, HttpServletResponse httpServletResponse) {
    File imageFile = new File(
            ApplicationPropertyManager.getApplicationProperty("iipimage.image.path") + imageName);

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

                BufferedImage page = null;
                if (reader.getNumImages(true) <= 2) {
                    logger.error(imageFile + " have " + reader.getNumImages(true)
                            + " level. Trying to render thumbnail image from level 1");
                    page = reader.read(0);
                } else {
                    page = reader.read(2);
                }

                if (page != null) {
                    RenderedOp thubmnailImage = null;
                    try {
                        double resizeFactor = thumbnailWidth / page.getWidth();

                        if (resizeFactor <= 1) {
                            ParameterBlock paramBlock = new ParameterBlock();
                            paramBlock.addSource(page); // The source image
                            paramBlock.add(resizeFactor); // The xScale
                            paramBlock.add(resizeFactor); // The yScale
                            paramBlock.add(0.0); // The x translation
                            paramBlock.add(0.0); // The y translation
                            RenderingHints qualityHints = new RenderingHints(RenderingHints.KEY_RENDERING,
                                    RenderingHints.VALUE_RENDER_QUALITY);
                            thubmnailImage = JAI.create("SubsampleAverage", paramBlock, qualityHints);
                        } else if (resizeFactor > 1) {
                            thubmnailImage = ScaleDescriptor.create(page, (float) resizeFactor,
                                    (float) resizeFactor, 0.0f, 0.0f,
                                    Interpolation.getInstance(Interpolation.INTERP_BICUBIC), null);
                        }

                        if ((thumbnailFormat != null) && (thumbnailFormat.toLowerCase().equals("jpeg"))) {
                            // replaced statement to control jpeg quality
                            // ImageIO.write(thubmnailImage, "jpeg",
                            // byteArrayOutputStream);
                            JPEGEncodeParam jpgparam = new JPEGEncodeParam();
                            jpgparam.setQuality(imageQuality);
                            ImageEncoder enc = ImageCodec.createImageEncoder("jpeg", byteArrayOutputStream,
                                    jpgparam);
                            enc.encode(thubmnailImage);
                        } else {
                            logger.error("Unmanaged thumbnail format " + thumbnailFormat);
                        }
                    } catch (IOException ioException) {
                        logger.error(ioException);
                    }
                }

                // preparing image for output
                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 (IIOException iioException) {
        if (iioException.getMessage().equals("Unsupported Image Type")) {
            logger.error("Unsupported Image Type " + imageFile);
        } else {
            logger.error(iioException);
        }
    } 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.photovault.image.ImageIOImage.java

/**
 Read the image (either original or proper thumbnail in the same file and subsample 
 it to save memory & time. The image is subsampled so that its reasolution is the
 smallest possible that is bigger than given limits. 
         /* w  w w .ja  v a2s . c om*/
 @param reader The image reader that is used for reading the image
 @param minWidth Minimum width of the subsampled image
 @param minHeight Minimum height of the subsampled iamge
         
 @return Subsampled image.
 */

private RenderedImage readSubsampled(ImageReader reader, int minWidth, int minHeight) throws IOException {
    /*
     We try to ensure that the thumbnail is actually from the original image
     by comparing aspect ratio of it to original. This is not a perfect check
     but it will usually catch the most typical errors (like having a the original
     rotated by RAW conversion SW but still the original EXIF thumbnail.
     */
    double origAspect = reader.getAspectRatio(0);
    double aspectAccuracy = 0.01;
    int minInstanceSide = Math.max(minWidth, minHeight);

    int numThumbs = 0;
    RenderedImage image = null;
    try {
        int numImages = reader.getNumImages(true);
        if (numImages > 0) {
            numThumbs = reader.getNumThumbnails(0);
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    if (numThumbs > 0 && isOkForThumbCreation(reader.getThumbnailWidth(0, 0), reader.getThumbnailHeight(0, 0),
            minWidth, minHeight, origAspect, aspectAccuracy)) {
        // There is a thumbanil that is big enough - use it

        log.debug("Original has thumbnail, size " + reader.getThumbnailWidth(0, 0) + " x "
                + reader.getThumbnailHeight(0, 0));
        image = reader.readThumbnail(0, 0);
        log.debug("Read thumbnail");
    } else {
        log.debug("No thumbnail in original");
        ImageReadParam param = reader.getDefaultReadParam();

        // Find the maximum subsampling rate we can still use for creating
        // a quality thumbnail. Some image format readers seem to have
        // problems with subsampling values (e.g. PNG sometimes crashed
        // the whole virtual machine, to for now let's do this only
        // with JPG.
        int subsampling = 1;
        if (reader.getFormatName().equals("JPEG")) {
            int minDim = Math.min(reader.getWidth(0), reader.getHeight(0));
            while (2 * minInstanceSide * subsampling < minDim) {
                subsampling *= 2;
            }
        }
        param.setSourceSubsampling(subsampling, subsampling, 0, 0);
        image = reader.read(0, param);
    }
    return image;
}

From source file:org.psystems.dicom.daemon.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  ww .  j a  v  a  2 s .  c o  m*/
    param.setWindowWidth(width);
    param.setVoiLutFunction(vlutFct);
    param.setPresentationState(prState);
    param.setPValue2Gray(pval2gray);
    param.setAutoWindowing(autoWindowing);
    ImageInputStream iis = ImageIO.createImageInputStream(src);
    BufferedImage bi;
    OutputStream out = null;
    try {
        reader.setInput(iis, false);
        if (reader.getNumImages(false) <= 0) {
            System.out.println("\nError: " + src + " - Don't haven any images!");
            return;
        }
        //            System.out.println("!!! frame="+frame+" p="+reader.getNumImages(false));
        bi = reader.read(frame - 1, param);
        if (bi == null) {
            System.out.println("\nError: " + src + " - couldn't read!");
            return;
        }
        out = new BufferedOutputStream(new FileOutputStream(dest));
        JPEGImageEncoder enc = JPEGCodec.createJPEGEncoder(out);
        enc.encode(bi);
    } finally {
        CloseUtils.safeClose(iis);
        CloseUtils.safeClose(out);
    }
    System.out.print('.');
}