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.hippoecm.frontend.plugins.gallery.imageutil.ImageUtils.java

/**
 * Converts image raster data to a JPEG with RGB color space. Only images with color space CMYK and YCCK are
 * converted, other images are left untouched.
 *
 * Rationale: Java's ImageIO can't process 4-component images and Java2D can't apply AffineTransformOp either,
 * so we have to convert raster data to a JPG with RGB color space.
 *
 * The technique used in this method is due to Mark Stephens, and free for any use. See
 * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4799903 or
 * http://www.mail-archive.com/java2d-interest@capra.eng.sun.com/msg03247.html
 *
 * @param is the image data/*from   www . j av  a 2 s  .  co m*/
 * @param colorModel the color model of the image
 * @return the RGB version of the supplied image
 */
public static InputStream convertToRGB(InputStream is, ColorModel colorModel)
        throws IOException, UnsupportedImageException {
    if (colorModel != ColorModel.CMYK && colorModel != ColorModel.YCCK) {
        return is;
    }

    // Get an ImageReader.
    ImageInputStream input = ImageIO.createImageInputStream(is);

    try {
        Iterator<ImageReader> readers = ImageIO.getImageReaders(input);
        if (readers == null || !readers.hasNext()) {
            throw new UnsupportedImageException("No ImageReaders found");
        }

        ImageReader reader = readers.next();
        reader.setInput(input);
        Raster raster = reader.readRaster(0, reader.getDefaultReadParam());

        int w = raster.getWidth();
        int h = raster.getHeight();
        byte[] rgb = new byte[w * h * 3];

        switch (colorModel) {
        case YCCK: {
            float[] Y = raster.getSamples(0, 0, w, h, 0, (float[]) null);
            float[] Cb = raster.getSamples(0, 0, w, h, 1, (float[]) null);
            float[] Cr = raster.getSamples(0, 0, w, h, 2, (float[]) null);
            float[] K = raster.getSamples(0, 0, w, h, 3, (float[]) null);

            for (int i = 0, imax = Y.length, base = 0; i < imax; i++, base += 3) {
                float k = 220 - K[i], y = 255 - Y[i], cb = 255 - Cb[i], cr = 255 - Cr[i];

                double val = y + 1.402 * (cr - 128) - k;
                val = (val - 128) * .65f + 128;
                rgb[base] = val < 0.0 ? (byte) 0 : val > 255.0 ? (byte) 0xff : (byte) (val + 0.5);

                val = y - 0.34414 * (cb - 128) - 0.71414 * (cr - 128) - k;
                val = (val - 128) * .65f + 128;
                rgb[base + 1] = val < 0.0 ? (byte) 0 : val > 255.0 ? (byte) 0xff : (byte) (val + 0.5);

                val = y + 1.772 * (cb - 128) - k;
                val = (val - 128) * .65f + 128;
                rgb[base + 2] = val < 0.0 ? (byte) 0 : val > 255.0 ? (byte) 0xff : (byte) (val + 0.5);
            }
            break;
        }
        case CMYK: {
            int[] C = raster.getSamples(0, 0, w, h, 0, (int[]) null);
            int[] M = raster.getSamples(0, 0, w, h, 1, (int[]) null);
            int[] Y = raster.getSamples(0, 0, w, h, 2, (int[]) null);
            int[] K = raster.getSamples(0, 0, w, h, 3, (int[]) null);

            for (int i = 0, imax = C.length, base = 0; i < imax; i++, base += 3) {
                int c = 255 - C[i];
                int m = 255 - M[i];
                int y = 255 - Y[i];
                int k = 255 - K[i];
                float kk = k / 255f;

                rgb[base] = (byte) (255 - Math.min(255f, c * kk + k));
                rgb[base + 1] = (byte) (255 - Math.min(255f, m * kk + k));
                rgb[base + 2] = (byte) (255 - Math.min(255f, y * kk + k));
            }
            break;
        }
        }

        // from other image types we know InterleavedRaster's can be
        // manipulated by AffineTransformOp, so create one of those.
        raster = Raster.createInterleavedRaster(new DataBufferByte(rgb, rgb.length), w, h, w * 3, 3,
                new int[] { 0, 1, 2 }, null);

        ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
        java.awt.image.ColorModel cm = new ComponentColorModel(cs, false, true, Transparency.OPAQUE,
                DataBuffer.TYPE_BYTE);
        BufferedImage convertedImage = new BufferedImage(cm, (WritableRaster) raster, true, null);

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(convertedImage, "jpg", os);

        return new ByteArrayInputStream(os.toByteArray());
    } finally {
        IOUtils.closeQuietly(is);
        if (input != null) {
            input.close();
        }
    }
}

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   ww w.j a v  a  2s .c o 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:it.geosolutions.imageio.plugins.nitronitf.ImageIOUtils.java

/**
 * Returns an ImageReader given the format, and sets the input source
 * //from  w ww  . j ava  2s  . c  o m
 * @param file
 * @return
 * @throws IOException
 */
public static ImageReader getImageReader(String format, Object input) throws IOException {
    ImageReader reader = null;
    Iterator<ImageReader> imageReaders = ImageIO.getImageReadersByFormatName(format);
    if (imageReaders.hasNext()) {
        reader = imageReaders.next();
        reader.setInput(input);
    }
    return reader;
}

From source file:it.geosolutions.imageio.plugins.nitronitf.ImageIOUtils.java

/**
 * Returns an ImageReader given the input file
 * //from ww w  . j  a  v a  2 s  .  co m
 * @param file
 * @return
 * @throws IOException
 */
public static ImageReader getImageReader(File file) throws IOException {
    String ext = FilenameUtils.getExtension(file.getName().toLowerCase());
    ImageReader reader = null;

    Iterator<ImageReader> imageReaders = ImageIO.getImageReadersBySuffix(ext);
    if (imageReaders.hasNext()) {
        reader = imageReaders.next();
        ImageInputStream stream = ImageIO.createImageInputStream(file);
        reader.setInput(stream);
    }
    return reader;
}

From source file:com.moviejukebox.scanner.artwork.PosterScanner.java

/**
 * Return the dimensions of a local image file
 *
 * @param imageFile//from  w  ww  .  j  a v a 2  s.  c  o  m
 * @return Dimension
 */
public static Dimension getFileImageSize(File imageFile) {
    Dimension imageSize = new Dimension(0, 0);

    ImageReader reader = null;

    try (ImageInputStream in = ImageIO.createImageInputStream(imageFile)) {
        @SuppressWarnings("rawtypes")
        Iterator readers = ImageIO.getImageReaders(in);
        if (readers.hasNext()) {
            reader = (ImageReader) readers.next();
            if (reader != null) {
                reader.setInput(in);
                return new Dimension(reader.getWidth(0), reader.getHeight(0));
            }
        }
    } catch (IOException | CMMException ex) {
        LOG.error("Failed to read image dimensions for {}", imageFile.getName());
        LOG.error("Error: {}", ex.getMessage());
        return imageSize;
    } finally {
        if (reader != null) {
            reader.dispose();
        }
    }

    return imageSize;
}

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

private static Document parse(InputStream source, Element instruction, PrintWriter logger) throws Exception {
    ImageReader reader;
    try {//from  w w w  . j  av a  2  s . com
        ImageInputStream iis = ImageIO.createImageInputStream(source);
        reader = ImageIO.getImageReaders(iis).next();
        reader.setInput(iis);
    } catch (Exception e) {
        logger.println("No image handlers available for the data stream. " + e.getMessage());
        throw e;
    }

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.newDocument();

    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t = tf.newTransformer();
    t.transform(new DOMSource(instruction), new DOMResult(doc));

    Element new_instruction = doc.getDocumentElement();

    int framesRead = 0;
    boolean containsFrames = false;
    Element framesElement = null;
    Element metadataElement = null;

    NodeList nodes = new_instruction.getChildNodes();
    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(reader.getFormatName().toLowerCase());
            } else if (node.getLocalName().equals("frames")) {
                framesElement = (Element) node;
                containsFrames = true;
            } else if (node.getLocalName().equals("metadata")) {
                metadataElement = (Element) node;
            } else if (node.getLocalName().equals("frame")) {
                int frame;
                String frameStr = ((Element) node).getAttribute("num");
                if (frameStr.length() == 0) {
                    frame = framesRead;
                    framesRead++;
                    ((Element) node).setAttribute("num", Integer.toString(frame));
                } else {
                    frame = Integer.parseInt(frameStr);
                    framesRead = frame + 1;
                }
                processFrame(reader, frame, node.getChildNodes(), logger);
                containsFrames = true;
            }
        }
    }

    if (containsFrames) {
        if (metadataElement != null) {
            IIOMetadata metadata = reader.getStreamMetadata();
            if (metadata != null) {
                String format = metadataElement.getAttribute("format");
                if (format.length() == 0) {
                    format = metadata.getNativeMetadataFormatName();
                }
                Node tree = metadata.getAsTree(format);
                t.transform(new DOMSource(tree), new DOMResult(metadataElement));
            }
        }
        if (framesElement != null) {
            boolean allowSearch = !reader.isSeekForwardOnly();
            int frames = reader.getNumImages(allowSearch);
            if (frames == -1) {
                try {
                    while (true) {
                        reader.read(framesRead);
                        framesRead++;
                    }
                } catch (Exception e) {
                    jlogger.log(Level.SEVERE, "", e);

                    frames = framesRead + 1;
                }
            }
            framesElement.setTextContent(Integer.toString(frames));
        }
    } else {
        processFrame(reader, 0, nodes, logger);
        framesRead = 1;
    }

    // t.transform(new DOMSource(doc), new StreamResult(System.out));
    return doc;
}

From source file:org.sleuthkit.autopsy.coreutils.ImageUtils.java

/**
 * Private template method designed to be used as the implementation of
 * public methods that pull particular (usually meta-)data out of a image
 * file./*from  w  w w. j a  v  a2  s .  c  o m*/
 *
 * @param file              the file to extract the data from
 * @param errorTemplate     a message template used to log errors. Should
 *                          take one parameter: the file's unique path or
 *                          name.
 * @param propertyExtractor an implementation of {@link PropertyExtractor}
 *                          used to retrieve the specific property.
 *
 * @return the the value of the property extracted by the given
 *         propertyExtractor
 *
 * @throws IOException if there was a problem reading the property from the
 *                     file.
 *
 * @see PropertyExtractor
 * @see #getImageHeight(org.sleuthkit.datamodel.AbstractFile)
 */
private static <T> T getImageProperty(AbstractFile file, final String errorTemplate,
        PropertyExtractor<T> propertyExtractor) throws IOException {
    try (InputStream inputStream = new BufferedInputStream(new ReadContentInputStream(file));) {
        try (ImageInputStream input = ImageIO.createImageInputStream(inputStream)) {
            if (input == null) {
                IIOException iioException = new IIOException("Could not create ImageInputStream.");
                LOGGER.log(Level.WARNING, errorTemplate + iioException.toString(), getContentPathSafe(file));
                throw iioException;
            }
            Iterator<ImageReader> readers = ImageIO.getImageReaders(input);

            if (readers.hasNext()) {
                ImageReader reader = readers.next();
                reader.setInput(input);
                try {

                    return propertyExtractor.extract(reader);
                } catch (IOException ex) {
                    LOGGER.log(Level.WARNING, errorTemplate + ex.toString(), getContentPathSafe(file));
                    throw ex;
                } finally {
                    reader.dispose();
                }
            } else {
                IIOException iioException = new IIOException("No ImageReader found.");
                LOGGER.log(Level.WARNING, errorTemplate + iioException.toString(), getContentPathSafe(file));

                throw iioException;
            }
        }
    }
}

From source file:nova.core.wrapper.mc.forge.v18.wrapper.render.BWClientRenderManager.java

@SideOnly(Side.CLIENT)
@Override//from   ww  w  .  ja  va 2s  . c  o m
public Vector2D getDimension(Texture texture) {
    ResourceLocation loc = toResourceLocation(texture);

    try {
        ImageInputStream in = ImageIO.createImageInputStream(
                Minecraft.getMinecraft().getResourceManager().getResource(loc).getInputStream());
        Iterator<ImageReader> readers = ImageIO.getImageReaders(in);
        if (readers.hasNext()) {
            ImageReader reader = readers.next();
            try {
                reader.setInput(in);
                return new Vector2D(reader.getWidth(0), reader.getHeight(0));
            } finally {
                reader.dispose();
            }
        }
    } catch (Exception e) {
        throw new RenderException("Couldn't load texture " + texture.getPath(), e);
    }
    return new Vector2D(16, 16);
}

From source file:nova.core.wrapper.mc.forge.v17.wrapper.render.BWClientRenderManager.java

@SideOnly(Side.CLIENT)
@Override/*  ww w  . jav  a2s.c  o  m*/
public Vector2D getDimension(Texture texture) {
    ResourceLocation loc = toResourceLocation(texture);

    try {
        ImageInputStream in = ImageIO.createImageInputStream(
                Minecraft.getMinecraft().getResourceManager().getResource(loc).getInputStream());
        Iterator<ImageReader> readers = ImageIO.getImageReaders(in);
        if (readers.hasNext()) {
            ImageReader reader = readers.next();
            try {
                reader.setInput(in);
                return new Vector2D(reader.getWidth(0), reader.getHeight(0));
            } finally {
                reader.dispose();
            }
        }
    } catch (Exception e) {
        throw new RenderException("Couldn't load texture " + texture.getPath(), e);
    }
    return super.getDimension(texture);
}

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

@Override
public void makeKeepToLocal(HtmlElement element) throws IOException {
    try {// ww  w  . jav  a2s.  c  om
        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());
    }

}