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:openthinks.others.htmlunit.PageKeeper.java

private StringBuffer keepStyleReference(String styleCtx) {
    Matcher matcher = RESOURCE_STYLE_REFERENCE_PATTERN.matcher(styleCtx);
    File refDir = new File(keepDir, RESOURCE_STYLE_REFERENCE_DIR);
    if (!refDir.exists())
        refDir.mkdirs();//from  ww w.j  a v  a2 s . c om
    StringBuffer sb = new StringBuffer();
    while (matcher.find()) {
        String relativeURL = matcher.group(1);
        String styleRefUrl = getFullyQualifiedUrl(relativeURL);
        String styleRefName = getResourceName(styleRefUrl);
        String styleRefCtx = "";
        File keepFile = new File(refDir, styleRefName);
        WebResponse wrp = null;
        try {
            checkIfAlreadExist(keepFile);
            wrp = getResourceResponse(styleRefUrl);
            if (wrp.getContentType().startsWith("image") || wrp.getContentType().startsWith("IMAGE")) {
                ImageInputStream iis = ImageIO.createImageInputStream(wrp.getContentAsStream());
                Iterator<ImageReader> iter = ImageIO.getImageReaders(iis);
                ImageReader imageReader = iter.next();
                imageReader.setInput(iis);
                ImageIO.write(imageReader.read(0), imageReader.getFormatName(), keepFile);
            } else {
                styleRefCtx = wrp.getContentAsString("UTF-8");
                store(styleRefCtx, keepFile);
            }
            matcher.appendReplacement(sb, "url(" + RESOURCE_STYLE_REFERENCE_URL + "/" + styleRefName + ")");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            matcher.appendReplacement(sb, "url(" + RESOURCE_STYLE_REFERENCE_URL + "/" + styleRefName + ")");
        } catch (NoSuchElementException e) {
            if (wrp != null) {
                styleRefCtx = wrp.getContentAsString("UTF-8");
                store(styleRefCtx, keepFile);
                matcher.appendReplacement(sb, "url(" + RESOURCE_STYLE_REFERENCE_URL + "/" + styleRefName + ")");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    matcher.appendTail(sb);
    return sb;
}

From source file:com.alibaba.simpleimage.codec.jpeg.JPEGDecodePerformanceTest.java

protected DecodeFacade getJDKDecoder() {
    DecodeFacade d = new DecodeFacade() {

        public BufferedImage decode(InputStream img) throws IOException {
            javax.imageio.stream.ImageInputStream stream = null;

            try {
                stream = ImageIO.createImageInputStream(img);
                Iterator<ImageReader> readers = ImageIO.getImageReaders(stream);
                ImageReader reader = null;
                while (readers.hasNext()) {
                    reader = readers.next();
                    if (reader.canReadRaster()) {
                        break;
                    }//from  w w  w . ja  v a 2s .com
                }

                reader.setInput(stream);
                BufferedImage bi = reader.read(0);

                return bi;
            } finally {
                if (stream != null) {
                    stream.close();
                }
            }
        }

        public String getName() {
            return "JDK Decoder";
        }

    };

    return d;
}

From source file:uk.bl.wa.analyser.payload.FaceDetectionAnalyser.java

@Override
public void analyse(String source, ArchiveRecordHeader header, InputStream tikainput, SolrRecord solr) {
    // Set up metadata object to pass to parsers:
    Metadata metadata = new Metadata();
    // Skip large images:
    if (header.getLength() > max_size_bytes) {
        return;/*from ww  w  . ja va2  s  .  c o  m*/
    }

    // Only attempt to analyse a random sub-set of the data:
    // (prefixing with static test of a final value to allow JIT to fully
    // optimise out the "OR Math.random()" bit)
    if (sampleRate >= 1.0 || Math.random() < sampleRate) {
        // Increment number of images sampled:
        sampleCount++;

        // Attempt to extract faces etc.:
        if (this.extractFaces || this.extractDominantColours) {
            log.info("Attempting to parse image file: " + header.getUrl());
            final long deepStart = System.nanoTime();
            ParseRunner parser = new ParseRunner(fdp, tikainput, metadata, solr);
            try {
                TimeLimiter.run(parser, 30000L, false);
            } catch (Exception e) {
                log.error("WritableSolrRecord.extract(): " + e.getMessage());
                solr.addParseException("when scanning for faces", e);
            }
            // Store basic image data:
            solr.addField(SolrFields.IMAGE_HEIGHT, metadata.get(FaceDetectionParser.IMAGE_HEIGHT));
            solr.addField(SolrFields.IMAGE_WIDTH, metadata.get(FaceDetectionParser.IMAGE_WIDTH));
            solr.addField(SolrFields.IMAGE_SIZE, metadata.get(FaceDetectionParser.IMAGE_SIZE));
            if (this.extractFaces) {
                // Store faces in SOLR:
                for (String face : metadata.getValues(FaceDetectionParser.FACE_FRAGMENT_ID)) {
                    log.debug("Found a face!");
                    solr.addField(SolrFields.IMAGE_FACES, face);
                }
                int faces = metadata.getValues(FaceDetectionParser.FACE_FRAGMENT_ID).length;
                if (faces > 0)
                    solr.setField(SolrFields.IMAGE_FACES_COUNT, "" + faces);
            }
            if (this.extractDominantColours) {
                // Store colour:
                solr.addField(SolrFields.IMAGE_DOMINANT_COLOUR, metadata.get(FaceDetectionParser.DOM_COL));
                // TODO Extract multiple characteristic colours as well
            }
            Instrument.timeRel("WARCPayloadAnalyzers.analyze#total", "ImageAnalyzer.analyze#facesanddominant",
                    deepStart);
        } else { //images are enabled, we still want to extract image/height (fast)
            //This method takes 0.2ms for a large image. I can be done even faster if needed(but more complicated)).
            //see https://stackoverflow.com/questions/672916/how-to-get-image-height-and-width-using-java

            ImageInputStream input = null;
            ImageReader reader = null;
            try {
                input = ImageIO.createImageInputStream(tikainput);
                reader = ImageIO.getImageReaders(input).next();
                reader.setInput(input);
                // Get dimensions of first image in the stream, without decoding pixel values
                int width = reader.getWidth(0);
                int height = reader.getHeight(0);

                // Store basic image data:
                solr.addField(SolrFields.IMAGE_HEIGHT, "" + height);
                solr.addField(SolrFields.IMAGE_WIDTH, "" + width);
                solr.addField(SolrFields.IMAGE_SIZE, "" + (height * width));
            } catch (Exception e) {
                //it is known that (most) .ico and (all) .svg are not supported by java. Do not log, since it will spam.
                log.warn("Unable to extract image data for url:" + header.getUrl(), e);
            } finally {
                if (reader != null) {
                    reader.dispose();
                }
            }

        }
    }
}

From source file:org.apache.tika.parser.image.ImageParser.java

public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context)
        throws IOException, SAXException, TikaException {
    String type = metadata.get(Metadata.CONTENT_TYPE);
    if (type != null) {
        // If the old (pre-RFC7903) BMP mime type is given,
        //  fix it up to the new one, so Java is happy
        if (OLD_BMP_TYPE.toString().equals(type)) {
            type = MAIN_BMP_TYPE.toString();
        }/*  w w  w.  j a  v a2 s. co m*/

        try {
            Iterator<ImageReader> iterator = ImageIO.getImageReadersByMIMEType(type);
            if (iterator.hasNext()) {
                ImageReader reader = iterator.next();
                try {
                    try (ImageInputStream imageStream = ImageIO
                            .createImageInputStream(new CloseShieldInputStream(stream))) {
                        reader.setInput(imageStream);

                        metadata.set(Metadata.IMAGE_WIDTH, Integer.toString(reader.getWidth(0)));
                        metadata.set(Metadata.IMAGE_LENGTH, Integer.toString(reader.getHeight(0)));
                        metadata.set("height", Integer.toString(reader.getHeight(0)));
                        metadata.set("width", Integer.toString(reader.getWidth(0)));

                        loadMetadata(reader.getImageMetadata(0), metadata);
                    }
                } finally {
                    reader.dispose();
                }
            }

            // Translate certain Metadata tags from the ImageIO
            //  specific namespace into the general Tika one
            setIfPresent(metadata, "CommentExtensions CommentExtension", TikaCoreProperties.COMMENTS);
            setIfPresent(metadata, "markerSequence com", TikaCoreProperties.COMMENTS);
            setIfPresent(metadata, "Data BitsPerSample", Metadata.BITS_PER_SAMPLE);
        } catch (IIOException e) {
            // TIKA-619: There is a known bug in the Sun API when dealing with GIF images
            //  which Tika will just ignore.
            if (!(e.getMessage() != null && e.getMessage().equals("Unexpected block type 0!")
                    && type.equals("image/gif"))) {
                throw new TikaException(type + " parse error", e);
            }
        }
    }

    XHTMLContentHandler xhtml = new XHTMLContentHandler(handler, metadata);
    xhtml.startDocument();
    xhtml.endDocument();
}

From source file:org.apache.pdfbox.tools.imageio.TestImageIOUtils.java

/**
 * checks whether the compression of a TIFF file is as expected.
 *
 * @param filename Filename/*  ww w . jav a  2 s .  co m*/
 * @param expectedCompression expected TIFF compression
 *
 * @throws IOException if something goes wrong
 */
void checkTiffCompression(String filename, String expectedCompression) throws IOException {
    Iterator readers = ImageIO.getImageReadersBySuffix("tiff");
    ImageReader reader = (ImageReader) readers.next();
    ImageInputStream iis = ImageIO.createImageInputStream(new File(filename));
    reader.setInput(iis);
    IIOMetadata imageMetadata = reader.getImageMetadata(0);
    Element root = (Element) imageMetadata.getAsTree(STANDARD_METADATA_FORMAT);
    Element comprElement = (Element) root.getElementsByTagName("Compression").item(0);
    Node comprTypeNode = comprElement.getElementsByTagName("CompressionTypeName").item(0);
    String actualCompression = comprTypeNode.getAttributes().getNamedItem("value").getNodeValue();
    assertEquals("Incorrect TIFF compression in file " + filename, expectedCompression, actualCompression);
    iis.close();
    reader.dispose();
}

From source file:org.hippoecm.frontend.plugins.gallery.imageutil.ScaleImageOperationTest.java

private void checkImageDimensions(ScaleImageOperation scaleOp, String mimeType, int expectedWidth,
        int expectedHeight) throws IOException {
    assertEquals(expectedWidth, scaleOp.getScaledWidth());
    assertEquals(expectedHeight, scaleOp.getScaledHeight());

    ImageReader reader = ImageIO.getImageReadersByMIMEType(mimeType).next();
    ImageInputStream iis = null;/*from ww  w. j  av  a  2s . c  o  m*/
    try {
        iis = ImageIO.createImageInputStream(scaleOp.getScaledData());
        reader.setInput(iis);
        assertEquals(scaleOp.getScaledWidth(), reader.getWidth(0));
        assertEquals(scaleOp.getScaledHeight(), reader.getHeight(0));
    } finally {
        if (iis != null) {
            iis.close();
        }
    }
}

From source file:org.paxle.gui.impl.MenuManager.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse response)
        throws ServletException, IOException {
    if (req.getParameter("icon") != null) {
        String iconURL = req.getParameter("icon");
        BufferedImage img = null;

        String fileSuffix = null;
        int idx = iconURL.lastIndexOf(".");
        if (idx != -1)
            fileSuffix = iconURL.substring(idx + 1);
        if (fileSuffix != null) {
            Iterator<ImageReader> readers = ImageIO.getImageReadersBySuffix(fileSuffix);
            while (readers.hasNext() && img == null) {
                ImageReader reader = readers.next();

                InputStream input = null;
                try {
                    input = new URL(iconURL).openStream();
                    reader.setInput(ImageIO.createImageInputStream(input));
                    img = reader.read(0);
                } catch (Exception e) {
                    this.log("Unable to read image from " + iconURL, e);
                } finally {
                    if (input != null)
                        input.close();//from   www  .  j  ava 2  s  . c o m
                }
            }
        } else {
            img = ImageIO.read(new URL(iconURL));
        }

        if (img != null) {
            response.setHeader("Content-Type", "image/png");
            ImageIO.write(img, "png", response.getOutputStream());
        } else {
            response.sendError(404);
        }
    }
}

From source file:org.apache.pdfbox.tools.imageio.TestImageIOUtils.java

/**
 * checks whether the resolution of an image file is as expected.
 *
 * @param filename the name of the file//from ww  w .j  a  v  a 2s.  co m
 * @param expectedResolution the expected resolution
 *
 * @throws IOException if something goes wrong
 */
private void checkResolution(String filename, int expectedResolution) throws IOException {
    assertFalse("Empty file " + filename, new File(filename).length() == 0);
    String suffix = filename.substring(filename.lastIndexOf('.') + 1);
    if ("BMP".equals(suffix.toUpperCase())) {
        // BMP reader doesn't work
        checkBmpResolution(filename, expectedResolution);
        return;
    }
    Iterator readers = ImageIO.getImageReadersBySuffix(suffix);
    assertTrue("No image reader found for suffix " + suffix, readers.hasNext());
    ImageReader reader = (ImageReader) readers.next();
    ImageInputStream iis = ImageIO.createImageInputStream(new File(filename));
    assertNotNull("No ImageInputStream created for file " + filename, iis);
    reader.setInput(iis);
    IIOMetadata imageMetadata = reader.getImageMetadata(0);
    Element root = (Element) imageMetadata.getAsTree(STANDARD_METADATA_FORMAT);
    NodeList dimensionNodes = root.getElementsByTagName("Dimension");
    assertTrue("No resolution found in image file " + filename, dimensionNodes.getLength() > 0);
    Element dimensionElement = (Element) dimensionNodes.item(0);

    NodeList pixelSizeNodes = dimensionElement.getElementsByTagName("HorizontalPixelSize");
    assertTrue("No X resolution found in image file " + filename, pixelSizeNodes.getLength() > 0);
    Node pixelSizeNode = pixelSizeNodes.item(0);
    String val = pixelSizeNode.getAttributes().getNamedItem("value").getNodeValue();
    int actualResolution = (int) Math.round(25.4 / Double.parseDouble(val));
    assertEquals("X resolution doesn't match in image file " + filename, expectedResolution, actualResolution);

    pixelSizeNodes = dimensionElement.getElementsByTagName("VerticalPixelSize");
    assertTrue("No Y resolution found in image file " + filename, pixelSizeNodes.getLength() > 0);
    pixelSizeNode = pixelSizeNodes.item(0);
    val = pixelSizeNode.getAttributes().getNamedItem("value").getNodeValue();
    actualResolution = (int) Math.round(25.4 / Double.parseDouble(val));
    assertEquals("Y resolution doesn't match", expectedResolution, actualResolution);

    iis.close();
    reader.dispose();
}

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  w  w . j  a  v  a2 s .c  o  m
 * @throws Exception
 */
@Test
public void testRotatedGet() throws Exception {
    String request = "wcs?&service=WCS&request=GetCoverage&version=1.1.1&identifier=RotatedCad&BoundingBox=7.7634071540971386,45.14712131948007,7.76437367395267,45.14764567708965,urn:ogc:def:crs:OGC:1.3:CRS84&Format=image/tiff";
    MockHttpServletResponse response = getAsServletResponse(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:org.geoserver.wcs.GetCoverageTest.java

@Test
public void testRasterFilterGreen() 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 'green%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(0, pixel[0]);//www.  j a v  a 2s  . c  o m
    assertEquals(255, pixel[1]);
    assertEquals(0, pixel[2]);
}