Example usage for javax.imageio ImageReader read

List of usage examples for javax.imageio ImageReader read

Introduction

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

Prototype

public BufferedImage read(int imageIndex) throws IOException 

Source Link

Document

Reads the image indexed by imageIndex and returns it as a complete BufferedImage , using a default ImageReadParam .

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    ImageInputStream imageStream = ImageIO.createImageInputStream(new URL("").openStream());
    Iterator<ImageReader> readers = ImageIO.getImageReaders(imageStream);
    ImageReader reader = null;
    if (!readers.hasNext()) {
        imageStream.close();//from   w  ww . j a v  a 2  s  . c  om
        return;
    } else {
        reader = readers.next();
    }
    String formatName = reader.getFormatName();
    if (!formatName.equalsIgnoreCase("jpeg") && !formatName.equalsIgnoreCase("png")
            && !formatName.equalsIgnoreCase("gif")) {
        imageStream.close();
        return;
    }
    reader.setInput(imageStream, true, true);
    BufferedImage theImage = reader.read(0);
    reader.dispose();
    imageStream.close();
}

From source file:Main.java

static public void main(String args[]) throws Exception {
    FileInputStream fin = new FileInputStream("a.gif");
    Iterator readers = ImageIO.getImageReadersBySuffix("GIF");
    ImageReader imageReader = (ImageReader) readers.next();
    ImageInputStream iis = ImageIO.createImageInputStream(fin);
    imageReader.setInput(iis, false);// w w  w .j  ava  2  s. c  om

    imageReader.addIIOReadProgressListener(new IIOReadProgressListener() {
        public void imageComplete(ImageReader source) {
            System.out.println("image complete " + source);
        }

        public void imageProgress(ImageReader source, float percentageDone) {
            System.out.println("image progress " + source + ": " + percentageDone + "%");
        }

        public void imageStarted(ImageReader source, int imageIndex) {
            System.out.println("image #" + imageIndex + " started " + source);
        }

        public void readAborted(ImageReader source) {
            System.out.println("read aborted " + source);
        }

        public void sequenceComplete(ImageReader source) {
            System.out.println("sequence complete " + source);
        }

        public void sequenceStarted(ImageReader source, int minIndex) {
            System.out.println("sequence started " + source + ": " + minIndex);
        }

        public void thumbnailComplete(ImageReader source) {
            System.out.println("thumbnail complete " + source);
        }

        public void thumbnailProgress(ImageReader source, float percentageDone) {
            System.out.println("thumbnail started " + source + ": " + percentageDone + "%");
        }

        public void thumbnailStarted(ImageReader source, int imageIndex, int thumbnailIndex) {
            System.out.println("thumbnail progress " + source + ", " + thumbnailIndex + " of " + imageIndex);
        }
    });

    BufferedImage image = imageReader.read(0);

    Iterator imageWriters = ImageIO.getImageWritersBySuffix("JPG");
    ImageWriter imageWriter = (ImageWriter) imageWriters.next();
    File file = new File("b.JPG");
    ImageOutputStream ios = ImageIO.createImageOutputStream(file);
    imageWriter.setOutput(ios);
    imageWriter.write(image);
}

From source file:FileUtils.java

/**
 * Utility method to read image from disk and transform image to BufferedImage object
 * @param data - relative path to the image
 * @param format - file prefix of the image
 * @return BufferedImage representation of the image
 *
 *//*from   w ww . j ava  2s  . c  om*/
public static BufferedImage bitmapToImage(String data, String format) throws IOException {
    final InputStream inb = new FileInputStream(data);
    final ImageReader rdr = ImageIO.getImageReadersByFormatName(format).next();
    final ImageInputStream imageInput = ImageIO.createImageInputStream(inb);
    rdr.setInput(imageInput);
    final BufferedImage image = rdr.read(0);
    inb.close();
    return image;
}

From source file:it.reexon.lib.files.FileUtils.java

/**
 * Utility method to read image from disk and transform image to BufferedImage object 
 *  //w w  w.ja v a  2  s  .c  o  m
 * @param data - relative path to the image 
 * @param format - file prefix of the image 
 * @return BufferedImage representation of the image 
 *  
 */
public static BufferedImage bitmapToImage(InputStream is, String format) throws IOException {
    final ImageReader rdr = ImageIO.getImageReadersByFormatName(format).next();
    final ImageInputStream imageInput = ImageIO.createImageInputStream(is);
    rdr.setInput(imageInput);
    final BufferedImage image = rdr.read(0);
    is.close();
    return image;
}

From source file:org.sejda.sambox.pdmodel.graphics.image.JPEGFactory.java

private static BufferedImage readJpeg(Object fileOrStream) throws IOException {
    Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName("JPEG");
    ImageReader reader = null;
    while (readers.hasNext()) {
        reader = readers.next();/*from www  .j av  a2 s . co m*/
        if (reader.canReadRaster()) {
            break;
        }
    }
    requireIOCondition(nonNull(reader), "Cannot find an ImageIO reader for JPEG image");

    try (ImageInputStream iis = ImageIO.createImageInputStream(fileOrStream)) {
        reader.setInput(iis);
        ImageIO.setUseCache(false);
        return reader.read(0);
    } finally {
        reader.dispose();
    }
}

From source file:org.onehippo.forge.gallerymagick.core.command.ScalrProcessorUtils.java

/**
 * Resize the given image {@code sourceFile} with resizing it to {@code width} and {@code height}
 * and store the resized image to {@code targetFile}, with appending {@code extraOptions} in the command line if provided.
 * @param sourceFile source image file//from ww w .  jav  a2  s .  com
 * @param targetFile target image file
 * @param dimension image dimension
 * @param extraOptions extra command line options
 * @throws IOException if IO exception occurs
 */
public static void resizeImage(File sourceFile, File targetFile, ImageDimension dimension,
        String... extraOptions) throws IOException {
    if (dimension == null) {
        throw new IllegalArgumentException("Invalid dimension: " + dimension);
    }

    ImageReader reader = null;
    ImageWriter writer = null;

    try {
        reader = getImageReader(sourceFile);

        if (reader == null) {
            throw new IllegalArgumentException(
                    "Unsupported image file name extension for reading: " + sourceFile);
        }

        writer = getImageWriter(targetFile);

        if (writer == null) {
            throw new IllegalArgumentException(
                    "Unsupported image file name extension for writing: " + targetFile);
        }

        BufferedImage sourceImage = reader.read(0);
        BufferedImage resizedImage = Scalr.resize(sourceImage, Scalr.Method.QUALITY, Scalr.Mode.AUTOMATIC,
                dimension.getWidth(), dimension.getHeight());

        final ImageWriteParam writeParam = writer.getDefaultWriteParam();

        if (writeParam.canWriteCompressed()) {
            String[] compressionTypes = writeParam.getCompressionTypes();

            if (compressionTypes != null && compressionTypes.length > 0) {
                writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
                writeParam.setCompressionType(compressionTypes[0]);
                writeParam.setCompressionQuality(1.0f);
            }
        }

        final IIOImage iioImage = new IIOImage(resizedImage, null, null);
        writer.write(null, iioImage, writeParam);
    } finally {
        if (reader != null) {
            reader.dispose();
        }
        if (writer != null) {
            writer.dispose();
        }
    }
}

From source file:nl.b3p.kaartenbalie.service.KBImageTool.java

/** Reads an image from an http input stream.
 *
 * @param is Inputstream//from w  w  w.j a  v  a 2 s  .c  o m
 * @param mime String representing the mime type of the image.
 *
 * @return BufferedImage
 *
 * @throws Exception
 */
// <editor-fold defaultstate="" desc="readImage(GetMethod method, String mime) method.">
public static BufferedImage readImage(InputStream is, String mime, ServiceProviderRequest wmsRequest)
        throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int bytesRead = 0;
    byte[] buffer = new byte[2048];
    while (bytesRead != -1) {
        bytesRead = is.read(buffer, 0, buffer.length);
        if (bytesRead > 0)
            baos.write(buffer, 0, bytesRead);
    }

    if (mime.indexOf(";") != -1) {
        mime = mime.substring(0, mime.indexOf(";"));
    }
    String mimeType = getMimeType(mime);
    if (mimeType == null) {
        String message = baos.toString();
        message = message.replaceAll("(\\r|\\n)", "");
        log.error("Response from server not understood (mime = " + mime + "): " + message);
        throw new Exception("Response from server not understood (mime = " + mime + "): " + message);
    }

    ImageReader ir = getReader(mimeType);
    if (ir == null) {
        log.error("no reader available for imageformat: " + mimeType.substring(mimeType.lastIndexOf("/") + 1));
        throw new Exception(
                "no reader available for imageformat: " + mimeType.substring(mimeType.lastIndexOf("/") + 1));
    }

    //TODO Make smarter.. Possibly faster... But keep reporting!
    wmsRequest.setBytesReceived(new Long(baos.size()));
    ImageInputStream stream = ImageIO.createImageInputStream(new ByteArrayInputStream(baos.toByteArray()));
    ir.setInput(stream, true);
    try {
        //if image is a png, has no alpha and has a tRNS then make that color transparent.
        BufferedImage i = ir.read(0);
        if (!i.getColorModel().hasAlpha() && ir.getImageMetadata(0) instanceof PNGMetadata) {
            PNGMetadata metadata = (PNGMetadata) ir.getImageMetadata(0);
            if (metadata.tRNS_present) {
                int alphaPix = (metadata.tRNS_red << 16) | (metadata.tRNS_green << 8) | (metadata.tRNS_blue);
                BufferedImage tmp = new BufferedImage(i.getWidth(), i.getHeight(), BufferedImage.TYPE_INT_ARGB);
                for (int x = 0; x < i.getWidth(); x++) {
                    for (int y = 0; y < i.getHeight(); y++) {
                        int rgb = i.getRGB(x, y);
                        rgb = (rgb & 0xFFFFFF) == alphaPix ? alphaPix : rgb;
                        tmp.setRGB(x, y, rgb);
                    }
                }
                i = tmp;
            }
        }
        return i;
    } finally {
        ir.dispose();
    }
}

From source file:openthinks.others.webpages.agent.HtmlImageResourceAgent.java

@Override
public void makeKeepToLocal(HtmlElement element) throws IOException {
    try {/* ww w .jav  a2s . com*/
        WebResponse wrp = keeper.loadWebResponse(keeper.getResourceURL());
        if ("image/svg+xml".equalsIgnoreCase(wrp.getContentType())) {//issue for svg image
            throw new Exception("SVG image.");
        }
        ImageInputStream iis = ImageIO.createImageInputStream(wrp.getContentAsStream());
        Iterator<ImageReader> iter = ImageIO.getImageReaders(iis);
        if (iter.hasNext()) {
            ImageReader imageReader = iter.next();
            imageReader.setInput(iis);
            ImageIO.write(imageReader.read(0), imageReader.getFormatName(), new File(keeper.getResourcePath()));
        }
    } catch (Exception e) {
        ProcessLogger.info(CommonUtilities.getCurrentInvokerMethod(), e.getMessage());
        WebResponse wrp = keeper.loadWebResponse(keeper.getResourceURL());
        storeBinaryResource(wrp.getContentAsStream());
    }

}

From source file:com.occamlab.te.parsers.ImageParser.java

private static Node processFrame(ImageReader reader, int frame, NodeList nodes, PrintWriter logger)
        throws Exception {
    if (nodes.getLength() == 0) {
        return null;
    }/*from www  .ja  va2 s  .  c o m*/
    String formatName = reader.getFormatName().toLowerCase(); // 2011-09-08
                                                              // PwD
    BufferedImage image = reader.read(frame);

    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            // System.out.println(node.getLocalName());
            if (node.getLocalName().equals("type")) {
                node.setTextContent(formatName); // 2011-09-08 PwD was
                                                 // reader.getFormatName().toLowerCase()
            } else if (node.getLocalName().equals("height")) {
                node.setTextContent(Integer.toString(image.getHeight()));
            } else if (node.getLocalName().equals("width")) {
                node.setTextContent(Integer.toString(image.getWidth()));
            } else if (node.getLocalName().equals("metadata")) {
                try { // 2011--08-23 PwD
                    IIOMetadata metadata = reader.getImageMetadata(frame);
                    if (metadata != null) {
                        String format = ((Element) node).getAttribute("format");
                        if (format.length() == 0) {
                            format = metadata.getNativeMetadataFormatName();
                        }
                        Node tree = metadata.getAsTree(format);
                        TransformerFactory tf = TransformerFactory.newInstance();
                        Transformer t = tf.newTransformer();
                        t.transform(new DOMSource(tree), new DOMResult(node));
                    }
                } catch (javax.imageio.IIOException e) { // 2011--08-23 PwD
                    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                    DocumentBuilder db = dbf.newDocumentBuilder();
                    Document doc = db.newDocument();
                    String format = reader.getFormatName().toLowerCase();
                    String formatEltName = "javax_imageio_" + format + "_1.0";
                    Element formatElt = doc.createElement(formatEltName);
                    TransformerFactory tf = TransformerFactory.newInstance();
                    Transformer t = tf.newTransformer();
                    t.transform(new DOMSource(formatElt), new DOMResult(node));
                }
            } else if (node.getLocalName().equals("model")) {
                int imagetype = -1;
                String model = ((Element) node).getAttribute("value");
                if (model.equals("MONOCHROME")) {
                    imagetype = BufferedImage.TYPE_BYTE_BINARY;
                } else if (model.equals("GRAY")) {
                    imagetype = BufferedImage.TYPE_BYTE_GRAY;
                } else if (model.equals("RGB")) {
                    imagetype = BufferedImage.TYPE_3BYTE_BGR;
                } else if (model.equals("ARGB")) {
                    imagetype = BufferedImage.TYPE_4BYTE_ABGR;
                } else {
                    model = "CUSTOM";
                }
                ((Element) node).setAttribute("value", model);
                BufferedImage buffImage = image;
                if (image.getType() != imagetype && imagetype != -1) {
                    buffImage = new BufferedImage(image.getWidth(), image.getHeight(), imagetype);
                    Graphics2D g2 = buffImage.createGraphics();
                    ImageTracker tracker = new ImageTracker();
                    boolean done = g2.drawImage(image, 0, 0, tracker);
                    if (!done) {
                        while (!tracker.done) {
                            sleep(50);
                        }
                    }
                }
                processBufferedImage(buffImage, formatName, node.getChildNodes());
            } else if (node.getLocalName().equals("transparency")) { // 2011-08-24
                                                                     // PwD
                int transparency = image.getTransparency();
                String transparencyName = null;
                switch (transparency) {
                case Transparency.OPAQUE: {
                    transparencyName = "Opaque";
                    break;
                }
                case Transparency.BITMASK: {
                    transparencyName = "Bitmask";
                    break;
                }
                case Transparency.TRANSLUCENT: {
                    transparencyName = "Translucent";
                    break;
                }
                default: {
                    transparencyName = "Unknown";
                }
                }
                node.setTextContent(transparencyName);

            } else if (node.getLocalName().equals("base64Data")) { // 2011-09-08
                                                                   // PwD
                String base64Data = getBase64Data(image, formatName, node);
                node.setTextContent(base64Data);
            } else {
                logger.println("ImageParser Error: Invalid tag " + node.getNodeName());
            }
        }
    }
    return null;
}

From source file:org.uiautomation.ios.server.servlet.ResourceServlet.java

private boolean validImage(File f) throws IOException {
    InputStream is = new FileInputStream(f);
    try {//from  ww  w  . j a  v a 2  s.c o  m
        //is = new FileInputStream(f);

        final ImageInputStream imageInputStream = ImageIO.createImageInputStream(is);
        final Iterator<ImageReader> imageReaders = ImageIO.getImageReaders(imageInputStream);
        if (!imageReaders.hasNext()) {
            // not an image
            return false;
        }
        final ImageReader imageReader = imageReaders.next();
        imageReader.setInput(imageInputStream);
        final BufferedImage image = imageReader.read(0);
        if (image == null) {
            // empty
            return false;
        }
        image.flush();
        return true;
    } catch (final IndexOutOfBoundsException e) {
        // truncated
        return false;
    } catch (final IIOException e) {
        if (e.getCause() instanceof EOFException) {
            // truncated
            return false;
        }
    } catch (Exception e) {
        return false;
    } finally {
        is.close();
    }
    return true;
}