Example usage for javax.imageio ImageReader setInput

List of usage examples for javax.imageio ImageReader setInput

Introduction

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

Prototype

public void setInput(Object input, boolean seekForwardOnly, boolean ignoreMetadata) 

Source Link

Document

Sets the input source to use to the given ImageInputStream or other Object .

Usage

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

/**
 * This method return image and tile information.
 * /*from   w w w. j a v  a  2 s .co 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  ww .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 w w  .  j ava2  s. com
 * @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

/**
 Load the image and/or metadata// ww  w  .ja  v  a  2  s .c o  m
 @param loadImage Load the image pixel data if <CODE>true</CODE>
 @param loadMetadata Load image metadata if <CODE>true</CODE>.
 @param minWidth Minimum width of the loaded image
 @param minHeight Minimum height of the loaded image
 @param isLowQualityAllowed If <code>true</code>, use larger subsampling 
 to speed up loading.
 */
private void load(boolean loadImage, boolean loadMetadata, int minWidth, int minHeight,
        boolean isLowQualityAllowed) {
    if (f != null && f.canRead()) {
        ImageReader reader = getImageReader(f);
        if (reader != null) {
            log.debug("Creating stream");
            ImageInputStream iis = null;
            try {
                iis = ImageIO.createImageInputStream(f);
                reader.setInput(iis, false, false);
                width = reader.getWidth(0);
                height = reader.getHeight(0);
                if (loadImage) {
                    RenderedImage ri = null;
                    if (isLowQualityAllowed) {
                        ri = readExifThumbnail(f);
                        if (ri == null || !isOkForThumbCreation(ri.getWidth(), ri.getHeight(), minWidth,
                                minHeight, reader.getAspectRatio(0), 0.01)) {
                            /*
                             EXIF thumbnail either did not exist or was unusable,
                             try to read subsampled version of original
                             */
                            ri = readSubsampled(reader, minWidth, minHeight);
                        }
                    } else {
                        /*
                         High quality image is requested.
                                 
                         If the image is very large, use subsampling anyway
                         to decrease memory consumption & speed up interactive 
                         operations. Anyway, most often user just views image 
                         at screen resolution
                         */
                        ImageReadParam param = reader.getDefaultReadParam();

                        if (minWidth * 2 < width && minHeight * 2 < height) {
                            param.setSourceSubsampling(2, 2, 0, 0);
                        }
                        ri = reader.read(0, param);

                    }
                    if (ri != null) {
                        /*
                         TODO: JAI seems to have problems in doing convolutions
                         for large image tiles. Split image to reasonably sized
                         tiles as a workaround for this.
                         */
                        ri = new TiledImage(ri, 256, 256);
                        image = new RenderedImageAdapter(ri);
                        originalSampleModel = image.getSampleModel();
                        originalColorModel = image.getColorModel();
                        final float[] DEFAULT_KERNEL_1D = { 0.25f, 0.5f, 0.25f };
                        ParameterBlock pb = new ParameterBlock();
                        KernelJAI kernel = new KernelJAI(DEFAULT_KERNEL_1D.length, DEFAULT_KERNEL_1D.length,
                                DEFAULT_KERNEL_1D.length / 2, DEFAULT_KERNEL_1D.length / 2, DEFAULT_KERNEL_1D,
                                DEFAULT_KERNEL_1D);
                        pb.add(kernel);
                        BorderExtender extender = BorderExtender.createInstance(BorderExtender.BORDER_COPY);
                        RenderingHints hints = JAI.getDefaultInstance().getRenderingHints();
                        if (hints == null) {
                            hints = new RenderingHints(JAI.KEY_BORDER_EXTENDER, extender);
                        } else {
                            hints.put(JAI.KEY_BORDER_EXTENDER, extender);
                        }

                        RenderedOp filter = new RenderedOp("convolve", pb, hints);
                        // javax.media.jai.operator.BoxFilterDescriptor.create( null, new Integer(2), new Integer(2), new Integer(0), new Integer(0), null );

                        // Add the subsampling operation.
                        pb = new ParameterBlock();
                        pb.addSource(filter);
                        pb.add(new Float(0.5F)).add(new Float(0.5F));
                        pb.add(new Float(0.0F)).add(new Float(0.0F));
                        pb.add(Interpolation.getInstance(Interpolation.INTERP_NEAREST));
                        RenderedOp downSampler = new RenderedOp("scale", pb, null);

                        renderableImage = RenderableDescriptor.createRenderable(image, downSampler, null, null,
                                null, null, null);
                    } else {
                        image = null;
                        renderableImage = null;
                    }
                    imageIsLowQuality = isLowQualityAllowed;
                }
                if (loadMetadata) {
                    readImageMetadata(reader);
                }
            } catch (Exception ex) {
                log.warn(ex.getMessage());
                ex.printStackTrace();
                return;
            }
        }
    }
}

From source file:org.apache.carbondata.sdk.file.ImageTest.java

public void binaryToCarbonWithHWD(String sourceImageFolder, String outputPath, String preDestPath,
        String sufAnnotation, final String sufImage, int numToWrite) throws Exception {
    int num = 1;//w  ww. jav  a 2s . com
    Field[] fields = new Field[7];
    fields[0] = new Field("height", DataTypes.INT);
    fields[1] = new Field("width", DataTypes.INT);
    fields[2] = new Field("depth", DataTypes.INT);
    fields[3] = new Field("binaryName", DataTypes.STRING);
    fields[4] = new Field("binary", DataTypes.BINARY);
    fields[5] = new Field("labelName", DataTypes.STRING);
    fields[6] = new Field("labelContent", DataTypes.STRING);

    byte[] originBinary = null;

    // read and write image data
    for (int j = 0; j < num; j++) {

        Object[] files = listFiles(sourceImageFolder, sufImage).toArray();

        int index = 0;

        if (null != files) {
            CarbonWriter writer = CarbonWriter.builder().outputPath(outputPath).withCsvInput(new Schema(fields))
                    .withBlockSize(256).writtenBy("SDKS3Example").withPageSizeInMb(1).build();

            for (int i = 0; i < files.length; i++) {
                if (0 == index % numToWrite) {
                    writer.close();
                    writer = CarbonWriter.builder().outputPath(outputPath).withCsvInput(new Schema(fields))
                            .withBlockSize(256).writtenBy("SDKS3Example").withPageSizeInMb(1).build();
                }
                index++;

                // read image and encode to Hex
                File file = new File((String) files[i]);
                System.out.println(file.getCanonicalPath());
                BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
                int depth = 0;
                boolean isGray;
                boolean hasAlpha;
                BufferedImage bufferedImage = null;
                try {
                    bufferedImage = ImageIO.read(file);
                    isGray = bufferedImage.getColorModel().getColorSpace().getType() == ColorSpace.TYPE_GRAY;
                    hasAlpha = bufferedImage.getColorModel().hasAlpha();

                    if (isGray) {
                        depth = 1;
                    } else if (hasAlpha) {
                        depth = 4;
                    } else {
                        depth = 3;
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println(i);
                    ImageInputStream stream = new FileImageInputStream(new File(file.getCanonicalPath()));
                    Iterator<ImageReader> iter = ImageIO.getImageReaders(stream);

                    Exception lastException = null;
                    while (iter.hasNext()) {
                        ImageReader reader = null;
                        try {
                            reader = (ImageReader) iter.next();
                            ImageReadParam param = reader.getDefaultReadParam();
                            reader.setInput(stream, true, true);
                            Iterator<ImageTypeSpecifier> imageTypes = reader.getImageTypes(0);

                            while (imageTypes.hasNext()) {
                                ImageTypeSpecifier imageTypeSpecifier = imageTypes.next();
                                System.out
                                        .println(imageTypeSpecifier.getColorModel().getColorSpace().getType());
                                int bufferedImageType = imageTypeSpecifier.getBufferedImageType();
                                if (bufferedImageType == BufferedImage.TYPE_BYTE_GRAY) {
                                    param.setDestinationType(imageTypeSpecifier);
                                    break;
                                }
                            }
                            bufferedImage = reader.read(0, param);
                            isGray = bufferedImage.getColorModel().getColorSpace()
                                    .getType() == ColorSpace.TYPE_GRAY;
                            hasAlpha = bufferedImage.getColorModel().hasAlpha();

                            if (isGray) {
                                depth = 1;
                            } else if (hasAlpha) {
                                depth = 4;
                            } else {
                                depth = 3;
                            }
                            if (null != bufferedImage)
                                break;
                        } catch (Exception e2) {
                            lastException = e2;
                        } finally {
                            if (null != reader)
                                reader.dispose();
                        }
                    }
                    // If you don't have an image at the end of all readers
                    if (null == bufferedImage) {
                        if (null != lastException) {
                            throw lastException;
                        }
                    }
                } finally {
                    originBinary = new byte[bis.available()];
                    while ((bis.read(originBinary)) != -1) {
                    }

                    String txtFileName = file.getCanonicalPath().split(sufImage)[0] + sufAnnotation;
                    BufferedInputStream txtBis = new BufferedInputStream(new FileInputStream(txtFileName));
                    String txtValue = null;
                    byte[] txtBinary = null;
                    txtBinary = new byte[txtBis.available()];
                    while ((txtBis.read(txtBinary)) != -1) {
                        txtValue = new String(txtBinary, "UTF-8");
                    }
                    // write data
                    writer.write(new Object[] { bufferedImage.getHeight(), bufferedImage.getWidth(), depth,
                            file.getCanonicalPath(), originBinary, txtFileName, txtValue.replace("\n", "") });
                    bis.close();
                }
            }
            writer.close();
        }
    }

    CarbonReader reader = CarbonReader.builder(outputPath).build();

    System.out.println("\nData:");
    int i = 0;
    while (i < 20 && reader.hasNext()) {
        Object[] row = (Object[]) reader.readNextRow();

        byte[] outputBinary = (byte[]) row[1];
        System.out.println(row[2] + " " + row[3] + " " + row[4] + " " + row[5] + " image size:"
                + outputBinary.length + " " + row[0]);

        // save image, user can compare the save image and original image
        String destString = preDestPath + i + sufImage;
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destString));
        bos.write(outputBinary);
        bos.close();
        i++;
    }
    System.out.println("\nFinished");
    reader.close();
}

From source file:org.geotools.coverage.io.util.Utilities.java

/**
 * Returns a {@code PlanarImage} given a set of parameter specifying the type of read operation to be performed.
 * /* ww  w .j  a v  a2s  . com*/
 * @param imageIndex
 * 
 * @param new FileImageInputStreamExtImplinput the input {@code ImageInputStream} to be used for reading the image.
 * @param useJAI {@code true} if we need to use a JAI ImageRead operation, {@code false} if we need a simple direct {@code ImageReader.read(...)}
 *        call.
 * @param imageReadParam an {@code ImageReadParam} specifying the read parameters
 * @param useMultithreading {@code true} if a JAI ImageRead operation is requested with support for multithreading. This parameter will be ignored
 *        if requesting a direct read operation.
 * @return the read {@code PlanarImage}
 * @throws IOException
 */
public static PlanarImage readImage(final ImageReaderSpi spi, final Object input, final int imageIndex,
        final boolean useJAI, final ImageReadParam imageReadParam, final boolean useMultithreading)
        throws IOException {
    ImageInputStream paramInput = null;
    if (input instanceof File) {
        paramInput = new FileImageInputStreamExtImpl((File) input);
    } else if (input instanceof FileImageInputStreamExt) {
        paramInput = (FileImageInputStreamExt) input;
    } else if (input instanceof URIImageInputStream) {
        paramInput = (URIImageInputStream) input;
    } else if (input instanceof URL) {
        final URL tempURL = (URL) input;
        String protocol = tempURL.getProtocol();
        if (protocol.equalsIgnoreCase("file")) {
            try {
                File file = it.geosolutions.imageio.utilities.Utilities.urlToFile(tempURL);
                paramInput = new FileImageInputStreamExtImpl(file);
            } catch (IOException e) {
                throw new RuntimeException("Failed to create a valid input stream ", e);
            }
        } else if (tempURL.getProtocol().toLowerCase().startsWith("http")
                || tempURL.getProtocol().equalsIgnoreCase("dods")) {
            try {
                paramInput = new URIImageInputStreamImpl(tempURL.toURI());
            } catch (URISyntaxException e) {
                throw new RuntimeException("Failed to create a valid input stream ", e);
            }
        }
    } else
        throw new IllegalArgumentException("Unsupported Input type:" + input);

    PlanarImage planarImage;
    ImageReader reader;
    ImageReaderSpi readerSpi = spi;
    if (useJAI) {
        final ParameterBlock pbjImageRead = new ParameterBlock();
        pbjImageRead.add(paramInput);
        pbjImageRead.add(imageIndex);
        pbjImageRead.add(Boolean.FALSE);
        pbjImageRead.add(Boolean.FALSE);
        pbjImageRead.add(Boolean.FALSE);
        pbjImageRead.add(null);
        pbjImageRead.add(null);
        pbjImageRead.add(imageReadParam);
        reader = readerSpi.createReaderInstance();
        pbjImageRead.add(reader);

        // Check if to use a simple JAI ImageRead operation or a
        // multithreaded one
        final String jaiOperation = useMultithreading ? "ImageReadMT" : "ImageRead";
        // final String jaiOperation = "ImageRead";
        /** TODO: SET HINTS */
        planarImage = JAI.create(jaiOperation, pbjImageRead, null);
    } else {
        reader = readerSpi.createReaderInstance();
        reader.setInput(paramInput, true, true);
        planarImage = PlanarImage.wrapRenderedImage(reader.read(imageIndex, imageReadParam));
        reader.dispose();
    }
    return planarImage;
}

From source file:org.geotools.gce.imagemosaic.GranuleDescriptor.java

GranuleOverviewLevelDescriptor getLevel(final int index) {

    //load level//from   w  w  w . j av  a2s .  c  om
    // create the base grid to world transformation
    ImageInputStream inStream = null;
    ImageReader reader = null;
    try {

        // get a stream
        assert cachedStreamSPI != null : "no cachedStreamSPI available!";
        inStream = cachedStreamSPI.createInputStreamInstance(granuleUrl, ImageIO.getUseCache(),
                ImageIO.getCacheDirectory());
        if (inStream == null)
            throw new IllegalArgumentException("Unable to create an inputstream for the granuleurl:"
                    + (granuleUrl != null ? granuleUrl : "null"));

        // get a reader and try to cache the relevant SPI
        if (cachedReaderSPI == null) {
            reader = ImageIOExt.getImageioReader(inStream);
            if (reader != null)
                cachedReaderSPI = reader.getOriginatingProvider();
        } else
            reader = cachedReaderSPI.createReaderInstance();
        if (reader == null)
            throw new IllegalArgumentException(
                    "Unable to get an ImageReader for the provided file " + granuleUrl.toString());
        final boolean ignoreMetadata = customizeReaderInitialization(reader, null);
        reader.setInput(inStream, false, ignoreMetadata);

        // call internal method which will close everything
        return getLevel(index, reader);

    } catch (IllegalStateException e) {

        // clean up
        try {
            if (inStream != null)
                inStream.close();
        } catch (Throwable ee) {

        } finally {
            if (reader != null)
                reader.dispose();
        }

        throw new IllegalArgumentException(e);

    } catch (IOException e) {

        // clean up
        try {
            if (inStream != null)
                inStream.close();
        } catch (Throwable ee) {
        } finally {
            if (reader != null)
                reader.dispose();
        }

        throw new IllegalArgumentException(e);
    }
}

From source file:de.cismet.cids.custom.objecteditors.wunda_blau.WebDavPicturePanel.java

/**
 * DOCUMENT ME!/*from w  w  w  .j  a  va  2  s  . c  o  m*/
 *
 * @param   fileName  DOCUMENT ME!
 *
 * @return  DOCUMENT ME!
 *
 * @throws  Exception  DOCUMENT ME!
 */
private BufferedImage downloadImageFromWebDAV(final String fileName) throws Exception {
    final InputStream iStream = webdavHelper.getFileFromWebDAV(fileName, webdavDirectory,
            getConnectionContext());
    try {
        final ImageInputStream iiStream = ImageIO.createImageInputStream(iStream);
        final Iterator<ImageReader> itReader = ImageIO.getImageReaders(iiStream);
        if (itReader.hasNext()) {
            final ImageReader reader = itReader.next();
            final ProgressMonitor monitor = new ProgressMonitor(this, "Bild wird bertragen...", "", 0, 100);
            //            monitor.setMillisToPopup(500);
            reader.addIIOReadProgressListener(new IIOReadProgressListener() {

                @Override
                public void sequenceStarted(final ImageReader source, final int minIndex) {
                }

                @Override
                public void sequenceComplete(final ImageReader source) {
                }

                @Override
                public void imageStarted(final ImageReader source, final int imageIndex) {
                    monitor.setProgress(monitor.getMinimum());
                }

                @Override
                public void imageProgress(final ImageReader source, final float percentageDone) {
                    if (monitor.isCanceled()) {
                        try {
                            iiStream.close();
                        } catch (final IOException ex) {
                            // NOP
                        }
                    } else {
                        monitor.setProgress(Math.round(percentageDone));
                    }
                }

                @Override
                public void imageComplete(final ImageReader source) {
                    monitor.setProgress(monitor.getMaximum());
                }

                @Override
                public void thumbnailStarted(final ImageReader source, final int imageIndex,
                        final int thumbnailIndex) {
                }

                @Override
                public void thumbnailProgress(final ImageReader source, final float percentageDone) {
                }

                @Override
                public void thumbnailComplete(final ImageReader source) {
                }

                @Override
                public void readAborted(final ImageReader source) {
                    monitor.close();
                }
            });

            final ImageReadParam param = reader.getDefaultReadParam();
            reader.setInput(iiStream, true, true);
            final BufferedImage result;
            try {
                result = reader.read(0, param);
            } finally {
                reader.dispose();
                iiStream.close();
            }
            return result;
        } else {
            return null;
        }
    } finally {
        IOUtils.closeQuietly(iStream);
    }
}

From source file:org.geotools.gce.imagemosaic.GranuleDescriptor.java

private void init(final BoundingBox granuleBBOX, final URL granuleUrl, final ImageReaderSpi suggestedSPI,
        final MultiLevelROI roiProvider, final boolean heterogeneousGranules,
        final boolean handleArtifactsFiltering, final Hints hints) {
    this.granuleBBOX = ReferencedEnvelope.reference(granuleBBOX);
    this.granuleUrl = granuleUrl;
    this.roiProvider = roiProvider;
    this.handleArtifactsFiltering = handleArtifactsFiltering;
    filterMe = handleArtifactsFiltering && roiProvider != null;

    // create the base grid to world transformation
    ImageInputStream inStream = null;
    ImageReader reader = null;
    try {/*from ww w  .  j a v a 2  s .co m*/
        //
        //get info about the raster we have to read
        //

        // get a stream
        if (cachedStreamSPI == null) {
            cachedStreamSPI = ImageIOExt.getImageInputStreamSPI(granuleUrl, true);
            if (cachedStreamSPI == null) {
                final File file = DataUtilities.urlToFile(granuleUrl);
                if (file != null) {
                    if (LOGGER.isLoggable(Level.WARNING)) {
                        LOGGER.log(Level.WARNING, Utils.getFileInfo(file));
                    }
                }
                throw new IllegalArgumentException(
                        "Unable to get an input stream for the provided granule " + granuleUrl.toString());
            }
        }
        assert cachedStreamSPI != null : "no cachedStreamSPI available!";
        inStream = cachedStreamSPI.createInputStreamInstance(granuleUrl, ImageIO.getUseCache(),
                ImageIO.getCacheDirectory());
        if (inStream == null) {
            final File file = DataUtilities.urlToFile(granuleUrl);
            if (file != null) {
                if (LOGGER.isLoggable(Level.WARNING)) {
                    LOGGER.log(Level.WARNING, Utils.getFileInfo(file));
                }
            }
            throw new IllegalArgumentException(
                    "Unable to get an input stream for the provided file " + granuleUrl.toString());
        }

        // get a reader and try to cache the suggested SPI first
        if (cachedReaderSPI == null) {
            inStream.mark();
            if (suggestedSPI != null && suggestedSPI.canDecodeInput(inStream)) {
                cachedReaderSPI = suggestedSPI;
                inStream.reset();
            } else {
                inStream.mark();
                reader = ImageIOExt.getImageioReader(inStream);
                if (reader != null)
                    cachedReaderSPI = reader.getOriginatingProvider();
                inStream.reset();
            }

        }
        if (reader == null) {
            if (cachedReaderSPI == null) {
                throw new IllegalArgumentException(
                        "Unable to get a ReaderSPI for the provided input: " + granuleUrl.toString());
            }
            reader = cachedReaderSPI.createReaderInstance();
        }

        if (reader == null)
            throw new IllegalArgumentException(
                    "Unable to get an ImageReader for the provided file " + granuleUrl.toString());
        boolean ignoreMetadata = customizeReaderInitialization(reader, hints);
        reader.setInput(inStream, false, ignoreMetadata);
        //get selected level and base level dimensions
        final Rectangle originalDimension = Utils.getDimension(0, reader);

        // build the g2W for this tile, in principle we should get it
        // somehow from the tile itself or from the index, but at the moment
        // we do not have such info, hence we assume that it is a simple
        // scale and translate
        this.geMapper = new GridToEnvelopeMapper(new GridEnvelope2D(originalDimension), granuleBBOX);
        geMapper.setPixelAnchor(PixelInCell.CELL_CENTER);//this is the default behavior but it is nice to write it down anyway
        this.baseGridToWorld = geMapper.createAffineTransform();

        // add the base level
        this.granuleLevels.put(Integer.valueOf(0),
                new GranuleOverviewLevelDescriptor(1, 1, originalDimension.width, originalDimension.height));

        ////////////////////// Setting overviewController ///////////////////////
        if (heterogeneousGranules) {
            // //
            //
            // Right now we are setting up overviewsController by assuming that
            // overviews are internal images as happens in TIFF images
            // We can improve this by leveraging on coverageReaders  
            //
            // //

            // Getting the first level descriptor
            final GranuleOverviewLevelDescriptor baseOverviewLevelDescriptor = granuleLevels.get(0);

            // Variables initialization
            final int numberOfOvervies = reader.getNumImages(true) - 1;
            final AffineTransform2D baseG2W = baseOverviewLevelDescriptor.getGridToWorldTransform();
            final int width = baseOverviewLevelDescriptor.getWidth();
            final int height = baseOverviewLevelDescriptor.getHeight();
            final double resX = AffineTransform2D.getScaleX0(baseG2W);
            final double resY = AffineTransform2D.getScaleY0(baseG2W);
            final double[] highestRes = new double[] { resX, resY };
            final double[][] overviewsResolution = new double[numberOfOvervies][2];

            // Populating overviews and initializing overviewsController
            for (int i = 0; i < numberOfOvervies; i++) {
                overviewsResolution[i][0] = (highestRes[0] * width) / reader.getWidth(i + 1);
                overviewsResolution[i][1] = (highestRes[1] * height) / reader.getHeight(i + 1);
            }
            overviewsController = new OverviewsController(highestRes, numberOfOvervies, overviewsResolution);
        }
        //////////////////////////////////////////////////////////////////////////

        if (hints != null && hints.containsKey(Utils.CHECK_AUXILIARY_METADATA)) {
            boolean checkAuxiliaryMetadata = (Boolean) hints.get(Utils.CHECK_AUXILIARY_METADATA);
            if (checkAuxiliaryMetadata) {
                checkPamDataset();
            }
        }

    } catch (IllegalStateException e) {
        throw new IllegalArgumentException(e);

    } catch (IOException e) {
        throw new IllegalArgumentException(e);
    } finally {
        // close/dispose stream and readers
        try {
            if (inStream != null) {
                inStream.close();
            }
        } catch (Throwable e) {
            throw new IllegalArgumentException(e);
        } finally {
            if (reader != null) {
                reader.dispose();
            }
        }
    }
}