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:com.google.testing.web.screenshotter.Screenshot.java

/**
 * Returns a BufferedImage of the screenshot. Every call to this returns a new copy of the image.
 *//*from   w  ww .  j  a  va  2 s  .  c  o  m*/
public BufferedImage asImage() throws IOException {
    ImageReader imageReader = ImageIO.getImageReadersByFormatName(FORMAT).next();
    imageReader.setInput(ImageIO.createImageInputStream(new ByteArrayInputStream(asBytes())), true);
    return imageReader.read(0);
}

From source file:com.gargoylesoftware.htmlunit.javascript.host.canvas.rendering.AwtRenderingBackend.java

/**
 * {@inheritDoc}//from w ww.  ja v a 2s .  co  m
 */
public void drawImage(final ImageReader imageReader, final int dxI, final int dyI) throws IOException {
    if (imageReader.getNumImages(true) != 0) {
        final BufferedImage img = imageReader.read(0);
        graphics2D_.drawImage(img, dxI, dyI, null);
    }
}

From source file:Main.java

public Main(String filename) throws Exception {
    FileInputStream fin = new FileInputStream(filename);
    String suffix = filename.substring(filename.lastIndexOf('.') + 1);
    System.out.println("suf " + suffix);
    Iterator readers = ImageIO.getImageReadersBySuffix(suffix);
    ImageReader imageReader = (ImageReader) readers.next();
    ImageInputStream iis = ImageIO.createImageInputStream(fin);
    imageReader.setInput(iis, false);//  w  ww.j a v  a2 s  . c o  m
    int num = imageReader.getNumImages(true);
    images = new BufferedImage[num];
    for (int i = 0; i < num; ++i) {
        images[i] = imageReader.read(i);
    }
    fin.close();
}

From source file:Main.java

public Main() throws Exception {
    String filename = "a.png";
    FileInputStream inputStream = new FileInputStream(filename);
    String extensionName = filename.substring(filename.lastIndexOf('.') + 1);
    Iterator readers = ImageIO.getImageReadersBySuffix(extensionName);
    ImageReader imageReader = (ImageReader) readers.next();
    ImageInputStream imageInputStream = ImageIO.createImageInputStream(inputStream);
    imageReader.setInput(imageInputStream, false);
    int num = imageReader.getNumImages(true);
    images = new BufferedImage[num];
    for (int i = 0; i < num; ++i) {
        images[i] = imageReader.read(i);
    }//ww w .j  a  v a  2s .  c o  m
    inputStream.close();
}

From source file:org.geoserver.wps.ppio.CoveragePPIOTest.java

private void testIsFormat(GridCoverage2D coverage, CoveragePPIO ppio, File encodedFile, String formatName)
        throws Exception {
    try (FileOutputStream fos = new FileOutputStream(encodedFile)) {
        ppio.encode(coverage, fos);/*from  w w w .  j a  va  2s. c  o  m*/
    }
    try (FileImageInputStream fis = new FileImageInputStream(encodedFile)) {
        ImageReader imageReader = null;
        try {
            imageReader = ImageIO.getImageReaders(fis).next();
            imageReader.setInput(fis);
            assertTrue(formatName.equalsIgnoreCase(imageReader.getFormatName()));
            assertNotNull(imageReader.read(0));
        } finally {
            if (imageReader != null) {
                try {
                    imageReader.dispose();
                } catch (Throwable t) {
                    // Ignore it.
                }
            }
        }
    }
}

From source file:org.jimcat.services.imagemanager.ImageUtil.java

/**
 * use this methode to load an image from a given byte array
 * /* ww w .  j a v a2 s.co m*/
 * @param data -
 *            the byte array containing an encoded image
 * @param quality
 *            the rendering quality
 * @return - a Buffered Image containing image. Its size is limited by
 *         SOURCE_BOUNDING_BOX constant
 * @throws IOException -
 *             if something goes wrong
 */
public static BufferedImage loadImage(byte[] data, ImageQuality quality) throws IOException {

    // read first element
    ImageReader reader = getReaderForImage(data);

    // get image dimension and calculate resulting image size
    int width = reader.getWidth(0);
    int height = reader.getHeight(0);
    Dimension size = getScaledDimension(width, height, SOURCE_BOUNDING_BOX, false);

    // performe read
    BufferedImage bi = null;
    try {
        if (USE_TILES) {
            // if image is smaller than a tile
            if (width <= IMAGE_TILE_SIZE.width && height <= IMAGE_TILE_SIZE.height) {
                bi = reader.read(0);
            } else {
                // prepaire reader
                ImageReadParam param = reader.getDefaultReadParam();

                // so image is bigger than a tile
                // a) check if reader supports source scaling
                if (param.canSetSourceRenderSize()) {
                    // fine => do it so
                    param.setSourceRenderSize(size);
                    bi = reader.read(0, param);
                } else {
                    // so, scaling has to be done by hand
                    bi = loadImageWithTiles(reader, size, quality);
                }
            }
        } else {
            bi = loadImageWithSubSampling(reader, size, quality);
        }
    } finally {
        reader.dispose();
    }
    return bi;
}

From source file:ImageIOTest.java

/**
 * Open a file and load the images./*from ww w. ja v  a  2  s  .com*/
 */
public void openFile() {
    JFileChooser chooser = new JFileChooser();
    chooser.setCurrentDirectory(new File("."));
    String[] extensions = ImageIO.getReaderFileSuffixes();
    chooser.setFileFilter(new FileNameExtensionFilter("Image files", extensions));
    int r = chooser.showOpenDialog(this);
    if (r != JFileChooser.APPROVE_OPTION)
        return;
    File f = chooser.getSelectedFile();
    Box box = Box.createVerticalBox();
    try {
        String name = f.getName();
        String suffix = name.substring(name.lastIndexOf('.') + 1);
        Iterator<ImageReader> iter = ImageIO.getImageReadersBySuffix(suffix);
        ImageReader reader = iter.next();
        ImageInputStream imageIn = ImageIO.createImageInputStream(f);
        reader.setInput(imageIn);
        int count = reader.getNumImages(true);
        images = new BufferedImage[count];
        for (int i = 0; i < count; i++) {
            images[i] = reader.read(i);
            box.add(new JLabel(new ImageIcon(images[i])));
        }
    } catch (IOException e) {
        JOptionPane.showMessageDialog(this, e);
    }
    setContentPane(new JScrollPane(box));
    validate();
}

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   w  w w .ja  va2s. c  o  m
    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:org.paxle.gui.impl.servlets.MetaDataIconServlet.java

@Override
protected void doRequest(HttpServletRequest request, HttpServletResponse response) {
    try {/*  w  w w.  j  av a  2  s  . co  m*/
        final Context context = this.getVelocityView().createContext(request, response);
        final String servicePID = request.getParameter(REQ_PARAM_SERVICEPID);

        if (servicePID != null) {
            // getting the metaDataTool
            final MetaDataTool tool = (MetaDataTool) context.get(MetaDataTool.TOOL_NAME);
            if (tool == null) {
                this.log("No MetaDataTool found");
                return;
            }

            final IMetaData metaData = tool.getMetaData(servicePID);
            if (metaData == null) {
                this.log(String.format("No metadata found for service with PID '%s'.", servicePID));
                return;
            }

            // getting the icon
            InputStream in = metaData.getIcon(16);
            if (in == null)
                in = this.getClass().getResourceAsStream("/resources/images/cog.png");

            // loading date
            final ByteArrayOutputStream bout = new ByteArrayOutputStream();
            IOUtils.copy(in, bout);
            bout.close();
            in.close();

            // trying to detect the mimetype of the image
            final ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
            String contentType = URLConnection.guessContentTypeFromStream(bin);
            bin.close();

            // reading the image
            BufferedImage img = null;
            Iterator<ImageReader> readers = null;
            if (contentType != null) {
                readers = ImageIO.getImageReadersByMIMEType(contentType);
                while (readers != null && readers.hasNext() && img == null) {
                    // trying the next reader
                    ImageReader reader = readers.next();

                    InputStream input = null;
                    try {
                        input = new ByteArrayInputStream(bout.toByteArray());
                        reader.setInput(ImageIO.createImageInputStream(input));
                        img = reader.read(0);
                    } catch (Exception e) {
                        this.log(String.format("Unable to read metadata icon for service with PID '%s'.",
                                servicePID), e);
                    } finally {
                        if (input != null)
                            input.close();
                    }
                }
            }

            if (img != null) {
                response.setHeader("Content-Type", "image/png");
                ImageIO.write(img, "png", response.getOutputStream());
                return;
            } else {
                response.sendError(404);
                return;
            }
        } else {
            response.sendError(500, "Invalid usage");
        }
    } catch (Throwable e) {
        this.log(String.format("Unexpected '%s'.", e.getClass().getName()), e);
    }
}

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   ww w.  j  a  v  a2s  .  c o  m
                }

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

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

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

    };

    return d;
}