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) 

Source Link

Document

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

Usage

From source file:org.geoserver.wcs.GetCoverageTest.java

@Test
public void testRasterFilterRed() throws Exception {
    String queryString = "wcs?identifier=" + getLayerId(MOSAIC) + "&request=getcoverage"
            + "&service=wcs&version=1.1.1&&format=image/tiff"
            + "&BoundingBox=0,0,1,1,urn:ogc:def:crs:EPSG:6.6:4326" + "&CQL_FILTER=location like 'red%25'";

    MockHttpServletResponse response = getAsServletResponse(queryString);

    // parse the multipart, check there are two parts
    Multipart multipart = getMultipart(response);
    assertEquals(2, multipart.getCount());
    BodyPart coveragePart = multipart.getBodyPart(1);
    assertEquals("image/tiff", coveragePart.getContentType());
    assertEquals("<theCoverage>", coveragePart.getHeader("Content-ID")[0]);

    // make sure we can read the coverage back
    ImageReader reader = ImageIO.getImageReadersByFormatName("tiff").next();
    reader.setInput(ImageIO.createImageInputStream(coveragePart.getInputStream()));
    RenderedImage image = reader.read(0);

    // check the pixel
    int[] pixel = new int[3];
    image.getData().getPixel(0, 0, pixel);
    assertEquals(255, pixel[0]);/*from w  ww.  j  a  v  a2  s  .  c o m*/
    assertEquals(0, pixel[1]);
    assertEquals(0, pixel[2]);
}

From source file:org.geoserver.wcs.GetCoverageTest.java

@Test
public void testReadNoGridCRS() throws Exception {
    String request = //
            "  <wcs:GetCoverage service=\"WCS\" version=\"1.1.1\" "
                    + "                   xmlns:wcs=\"http://www.opengis.net/wcs/1.1.1\" "
                    + "                   xmlns:gml=\"http://www.opengis.net/gml\""
                    + "                   xmlns:ows=\"http://www.opengis.net/ows/1.1\" >\n"
                    + "   <ows:Identifier>" + getLayerId(MockData.TASMANIA_DEM) + "   </ows:Identifier>\n"
                    + "            <wcs:DomainSubset>\n"
                    + "              <ows:BoundingBox crs=\"http://www.opengis.net/gml/srs/epsg.xml#4326\">\n"
                    + "                <ows:LowerCorner>-180.0 -90.0</ows:LowerCorner>\n"
                    + "                <ows:UpperCorner>180.0 90.0</ows:UpperCorner>\n"
                    + "              </ows:BoundingBox>\n" //
                    + "            </wcs:DomainSubset>\n" + "            <wcs:Output format=\"image/tiff\"/>\n"
                    + "          </wcs:GetCoverage>";

    MockHttpServletResponse response = postAsServletResponse("wcs", request);

    // parse the multipart, check there are two parts
    Multipart multipart = getMultipart(response);
    assertEquals(2, multipart.getCount());
    BodyPart coveragePart = multipart.getBodyPart(1);
    assertEquals("image/tiff", coveragePart.getContentType());
    assertEquals("<theCoverage>", coveragePart.getHeader("Content-ID")[0]);

    // make sure we can read the coverage back
    ImageReader reader = ImageIO.getImageReadersByFormatName("tiff").next();
    reader.setInput(ImageIO.createImageInputStream(coveragePart.getInputStream()));
    RenderedImage image = reader.read(0);
}

From source file:org.geoserver.wcs.GetCoverageTest.java

/**
 * This tests just ended up throwing an exception as the coverage being encoded
 * was too large due to a bug in the scales estimation
 * /*from   w  ww  .  j a v  a 2  s. c o m*/
 * @throws Exception
 */
@Test
public void testRotatedPost() throws Exception {
    String request = "<GetCoverage xmlns=\"http://www.opengis.net/wcs/1.1.1\" xmlns:gml=\"http://www.opengis.net/gml\"\n"
            + "             xmlns:ows11=\"http://www.opengis.net/ows/1.1\"\n"
            + "             xmlns:ows=\"http://www.opengis.net/ows/1.1\"\n"
            + "             xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \r\n" + //
            "             xmlns:wcs=\"http://schemas.opengis.net/wcs/1.1.1\"\n"
            + "             xmlns:xlink=\"http://www.w3.org/1999/xlink\"\n" + "             service=\"WCS\"\n"
            + "             version=\"1.1.1\"\n"
            + "             xsi:schemaLocation=\"http://www.opengis.net/wcs/1.1.1 http://schemas.opengis.net/wcs/1.1.1/wcsAll.xsd\">\n"
            + "   <ows11:Identifier>RotatedCad</ows11:Identifier>\n" + "   <DomainSubset>\n"
            + "      <ows11:BoundingBox crs=\"urn:ogc:def:crs:OGC:1.3:CRS84\">\n"
            + "         <ows11:LowerCorner>7.7634301664746515 45.14713380418506</ows11:LowerCorner>\n"
            + "         <ows11:UpperCorner>7.764350661575157 45.14763319238466</ows11:UpperCorner>\n"
            + "      </ows11:BoundingBox>\n" + "   </DomainSubset>\n" + "   <Output format=\"image/tiff\"/>\n"
            + "</GetCoverage>";

    MockHttpServletResponse response = postAsServletResponse("wcs", request);

    // parse the multipart, check there are two parts
    Multipart multipart = getMultipart(response);
    assertEquals(2, multipart.getCount());
    BodyPart coveragePart = multipart.getBodyPart(1);
    assertEquals("image/tiff", coveragePart.getContentType());
    assertEquals("<theCoverage>", coveragePart.getHeader("Content-ID")[0]);

    // make sure we can read the coverage back
    ImageReader reader = ImageIO.getImageReadersByFormatName("tiff").next();
    reader.setInput(ImageIO.createImageInputStream(coveragePart.getInputStream()));
    RenderedImage image = reader.read(0);

    // check the image is suitably small (without requiring an exact size)
    assertTrue(image.getWidth() < 1000);
    assertTrue(image.getHeight() < 1000);
}

From source file:it.tidalwave.imageio.test.ImageReaderTestSupport.java

/*******************************************************************************************************************
 * /*  w w w . java 2  s  .co  m*/
 * 
 ******************************************************************************************************************/
@Nonnull
protected ImageReader getImageReader(final @Nonnull String path, final @Nonnull RAWImageReadParam readParam)
        throws IOException {
    logger.info("************* TESTING FILE: %s - %s", path, readParam);

    final File file = getTestFile(path);
    final ImageReader ir = ImageIO.getImageReaders(file).next();
    assertNotNull(ir);

    if (readParam != null) {
        ((RAWImageReader) ir).setDefaultReadParam(readParam);
    }

    ir.setInput(ImageIO.createImageInputStream(file));
    return ir;
}

From source file:org.psystems.dicomweb.Dcm2Dcm.java

/**
 * Recodes the images from the source transfer syntax, as read from the src
 * file, to the specified destination syntax.
 *//*  w ww .  j a v a  2  s. c om*/
public void recodeImages(File src, File dest) throws IOException {

    ImageReader reader = new DicomImageReaderSpi().createReaderInstance();
    ImageWriter writer = new DicomImageWriterSpi().createWriterInstance();
    FileImageInputStream input = new FileImageInputStream(src);
    reader.setInput(input);
    if (dest.exists())
        dest.delete();
    FileImageOutputStream output = new FileImageOutputStream(dest);
    writer.setOutput(output);
    DicomStreamMetaData streamMeta = (DicomStreamMetaData) reader.getStreamMetadata();
    DicomObject ds = streamMeta.getDicomObject();
    DicomStreamMetaData writeMeta = (DicomStreamMetaData) writer.getDefaultStreamMetadata(null);
    DicomObject newDs = new BasicDicomObject();
    ds.copyTo(newDs);
    writeMeta.setDicomObject(newDs);
    int frames = ds.getInt(Tag.NumberOfFrames, 1);
    LookupTable lut = prepareBitStrip(writeMeta, reader);
    newDs.putString(Tag.TransferSyntaxUID, VR.UI, destinationSyntax.uid());
    if (overwriteObject != null) {
        overwriteObject.copyTo(newDs);
    }
    writer.prepareWriteSequence(writeMeta);
    for (int i = 0; i < frames; i++) {
        WritableRaster r = (WritableRaster) reader.readRaster(i, null);
        ColorModel cm = ColorModelFactory.createColorModel(ds);
        BufferedImage bi = new BufferedImage(cm, r, false, null);
        if (lut != null) {
            lut.lookup(bi.getRaster(), bi.getRaster());
        }
        IIOImage iioimage = new IIOImage(bi, null, null);
        writer.writeToSequence(iioimage, null);
    }
    writer.endWriteSequence();
    output.close();
    input.close();
}

From source file:org.psystems.dicomweb.Dcm2DcmCopy.java

/**
 * Recodes the images from the source transfer syntax, as read from the src
 * file, to the specified destination syntax.
 *///from   ww  w.  j a  va  2s . com
public void recodeImages(File src, File dest) throws IOException {
    ImageReader reader = new DicomImageReaderSpi().createReaderInstance();
    ImageWriter writer = new DicomImageWriterSpi().createWriterInstance();
    FileImageInputStream input = new FileImageInputStream(src);
    reader.setInput(input);
    if (dest.exists())
        dest.delete();
    FileImageOutputStream output = new FileImageOutputStream(dest);
    writer.setOutput(output);
    DicomStreamMetaData streamMeta = (DicomStreamMetaData) reader.getStreamMetadata();
    DicomObject ds = streamMeta.getDicomObject();
    DicomStreamMetaData writeMeta = (DicomStreamMetaData) writer.getDefaultStreamMetadata(null);
    DicomObject newDs = new BasicDicomObject();
    ds.copyTo(newDs);
    writeMeta.setDicomObject(newDs);
    int frames = ds.getInt(Tag.NumberOfFrames, 1);
    LookupTable lut = prepareBitStrip(writeMeta, reader);
    newDs.putString(Tag.TransferSyntaxUID, VR.UI, destinationSyntax.uid());
    if (overwriteObject != null) {
        overwriteObject.copyTo(newDs);
    }
    writer.prepareWriteSequence(writeMeta);
    for (int i = 0; i < frames; i++) {
        WritableRaster r = (WritableRaster) reader.readRaster(i, null);
        ColorModel cm = ColorModelFactory.createColorModel(ds);
        BufferedImage bi = new BufferedImage(cm, r, false, null);
        if (lut != null) {
            lut.lookup(bi.getRaster(), bi.getRaster());
        }
        IIOImage iioimage = new IIOImage(bi, null, null);
        writer.writeToSequence(iioimage, null);
    }
    writer.endWriteSequence();
    output.close();
    input.close();
}

From source file:com.gargoylesoftware.htmlunit.html.HtmlImage.java

private void readImageIfNeeded() throws IOException {
    downloadImageIfNeeded();//from ww w. j  a v  a 2s  .  c o  m
    if (imageData_ == null) {
        if (null == imageWebResponse_) {
            throw new IOException("No image response available (src=" + getSrcAttribute() + ")");
        }
        final ImageInputStream iis = ImageIO.createImageInputStream(imageWebResponse_.getContentAsStream());
        final Iterator<ImageReader> iter = ImageIO.getImageReaders(iis);
        if (!iter.hasNext()) {
            iis.close();
            throw new IOException("No image detected in response");
        }
        final ImageReader imageReader = iter.next();
        imageReader.setInput(iis);
        imageData_ = new ImageData(imageReader);

        // dispose all others
        while (iter.hasNext()) {
            iter.next().dispose();
        }
    }
}

From source file:org.dita.dost.writer.ImageMetadataFilter.java

private Attributes readMetadata(final URI imgInput) {
    logger.info("Reading " + imgInput);
    final XMLUtils.AttributesBuilder a = new XMLUtils.AttributesBuilder();
    try {// w  ww .j a v  a2s.  c o  m
        InputStream in = null;
        ImageReader r = null;
        ImageInputStream iis = null;
        try {
            in = getInputStream(imgInput);
            iis = ImageIO.createImageInputStream(in);
            final Iterator<ImageReader> i = ImageIO.getImageReaders(iis);
            if (!i.hasNext()) {
                logger.info("Image " + imgInput + " format not supported");
            } else {
                r = i.next();
                r.setInput(iis);
                final int imageIndex = r.getMinIndex();
                a.add(DITA_OT_NS, ATTR_IMAGE_WIDTH, DITA_OT_PREFIX + ":" + ATTR_IMAGE_WIDTH, "CDATA",
                        Integer.toString(r.getWidth(imageIndex)));
                a.add(DITA_OT_NS, ATTR_IMAGE_HEIGHT, DITA_OT_PREFIX + ":" + ATTR_IMAGE_HEIGHT, "CDATA",
                        Integer.toString(r.getHeight(imageIndex)));
                final Element node = (Element) r.getImageMetadata(0).getAsTree("javax_imageio_1.0");
                final NodeList hs = node.getElementsByTagName("HorizontalPixelSize");
                if (hs != null && hs.getLength() == 1) {
                    final float v = Float.parseFloat(((Element) hs.item(0)).getAttribute("value"));
                    final int dpi = Math.round(MM_TO_INCH / v);
                    a.add(DITA_OT_NS, ATTR_HORIZONTAL_DPI, DITA_OT_PREFIX + ":" + ATTR_HORIZONTAL_DPI, "CDATA",
                            Integer.toString(dpi));
                }
                final NodeList vs = node.getElementsByTagName("VerticalPixelSize");
                if (vs != null && vs.getLength() == 1) {
                    final float v = Float.parseFloat(((Element) vs.item(0)).getAttribute("value"));
                    final int dpi = Math.round(MM_TO_INCH / v);
                    a.add(DITA_OT_NS, ATTR_VERTICAL_DPI, DITA_OT_PREFIX + ":" + ATTR_VERTICAL_DPI, "CDATA",
                            Integer.toString(dpi));
                }
            }
        } finally {
            if (r != null) {
                r.dispose();
            }
            if (iis != null) {
                iis.close();
            }
            if (in != null) {
                in.close();
            }
        }
    } catch (final Exception e) {
        logger.error("Failed to read image " + imgInput + " metadata: " + e.getMessage(), e);
    }
    return a.build();
}

From source file:org.photovault.image.ImageIOImage.java

/**
 * Parse JPEG metadata structure and store the data in metadata and exifData fields
 * @param top The metadata object tree in format "javax_imageio_jpeg_image_1.0"
 *//*from w  w w.  j  a v  a2s  .  c  om*/
private void parseJPEGMetadata(IIOMetadataNode top) {
    NodeList candidates = top.getElementsByTagName("unknown");
    for (int n = 0; n < candidates.getLength(); n++) {
        Node node = candidates.item(n);
        if (node instanceof IIOMetadataNode) {
            IIOMetadataNode m = (IIOMetadataNode) node;
            Object obj = m.getUserObject();
            if (obj instanceof byte[]) {
                byte[] data = (byte[]) obj;
                if (data[0] == 'E' && data[1] == 'x' && data[2] == 'i' && data[3] == 'f') {
                    log.debug("exif data found");
                    InputStream is = new ByteArrayInputStream(data, 6, data.length - 6);
                    try {
                        ImageInputStream metadataStream = ImageIO.createImageInputStream(is);
                        Iterator readers = ImageIO.getImageReadersByFormatName("TIFF");
                        if (readers.hasNext()) {
                            ImageReader reader = (ImageReader) readers.next();
                            reader.setInput(metadataStream);
                            IIOMetadata iioMetadata = reader.getImageMetadata(0);
                            this.metadata = TIFFDirectory.createFromMetadata(iioMetadata);
                            TIFFField exifField = this.metadata
                                    .getTIFFField(EXIFParentTIFFTagSet.TAG_EXIF_IFD_POINTER);
                        }
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                } else if (data.length > 28 && data[28] == 0) {
                    String id = null;
                    try {
                        id = new String(data, 0, 28, "utf-8");
                    } catch (UnsupportedEncodingException e) {
                        log.error(e);
                    }
                    if ("http://ns.adobe.com/xap/1.0/".equals(id)) {

                        // XMP metadata
                        try {
                            String xmpPacket = new String(data, 29, data.length - 29, "utf-8");
                            XMPMeta xmp = XMPMetaFactory.parseFromString(xmpPacket);
                            log.debug("Found XMP metadata");
                        } catch (XMPException e) {
                            log.warn("caught XMP exception while parsing metadata", e);
                        } catch (UnsupportedEncodingException e) {
                            log.error(e);
                        }
                    }
                }
            }
        }
    }
}

From source file:net.filterlogic.util.imaging.ToTIFF.java

/**
 * /*from w  ww.  j  a va2  s  . c  o  m*/
 * @param fileName
 */
public void test6(String fileName) {
    try {
        File f = new File(fileName);

        ImageInputStream imageInputStream = ImageIO.createImageInputStream(f);
        java.util.Iterator readers = ImageIO.getImageReaders(imageInputStream);
        ImageReader reader1 = (ImageReader) readers.next();
        ImageInputStream iis = ImageIO.createImageInputStream(new FileInputStream(f));
        reader1.setInput(iis);

        int number = reader1.getNumImages(true);
        Iterator writers = ImageIO.getImageWritersByFormatName("tiff");
        ImageWriter writer = (ImageWriter) writers.next();

        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        ImageOutputStream ios = null;
        BufferedImage img = null;

        for (int i = 0; i < number; i++) {
            img = reader1.read(i);
            ios = ImageIO.createImageOutputStream(byteOut);
            writer.setOutput(ios);
            writer.write(img);
            ios.flush();
            img.flush();
            byteOut.flush();
        }

    } catch (Exception e) {
        System.out.println(e.toString());
    }

}