Search in sources :

Example 16 with IIOMetadata

use of javax.imageio.metadata.IIOMetadata in project jdk8u_jdk by JetBrains.

the class BooleanAttributes method test.

public static void test(String mimeType, boolean useStreamMeta, String metaXml, String... boolXpaths) throws Exception {
    BufferedImage img = new BufferedImage(16, 16, BufferedImage.TYPE_INT_RGB);
    ImageWriter iw = ImageIO.getImageWritersByMIMEType(mimeType).next();
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    ImageOutputStream ios = new MemoryCacheImageOutputStream(os);
    iw.setOutput(ios);
    ImageWriteParam param = null;
    IIOMetadata streamMeta = iw.getDefaultStreamMetadata(param);
    IIOMetadata imageMeta = iw.getDefaultImageMetadata(new ImageTypeSpecifier(img), param);
    IIOMetadata meta = useStreamMeta ? streamMeta : imageMeta;
    Source src = new StreamSource(new StringReader(metaXml));
    DOMResult dst = new DOMResult();
    transform(src, dst);
    Document doc = (Document) dst.getNode();
    Element node = doc.getDocumentElement();
    String metaFormat = node.getNodeName();
    // Verify that the default metadata gets formatted correctly.
    verify(meta.getAsTree(metaFormat), boolXpaths, false);
    meta.mergeTree(metaFormat, node);
    // Verify that the merged metadata gets formatte correctly.
    verify(meta.getAsTree(metaFormat), boolXpaths, true);
    iw.write(streamMeta, new IIOImage(img, null, imageMeta), param);
    iw.dispose();
    ios.close();
    ImageReader ir = ImageIO.getImageReader(iw);
    byte[] bytes = os.toByteArray();
    if (bytes.length == 0)
        throw new AssertionError("Zero length image file");
    ByteArrayInputStream is = new ByteArrayInputStream(bytes);
    ImageInputStream iis = new MemoryCacheImageInputStream(is);
    ir.setInput(iis);
    if (useStreamMeta)
        meta = ir.getStreamMetadata();
    else
        meta = ir.getImageMetadata(0);
    // Verify again after writing and re-reading the image
    verify(meta.getAsTree(metaFormat), boolXpaths, true);
}
Also used : DOMResult(javax.xml.transform.dom.DOMResult) StreamSource(javax.xml.transform.stream.StreamSource) Element(org.w3c.dom.Element) MemoryCacheImageInputStream(javax.imageio.stream.MemoryCacheImageInputStream) ImageInputStream(javax.imageio.stream.ImageInputStream) ImageWriter(javax.imageio.ImageWriter) MemoryCacheImageInputStream(javax.imageio.stream.MemoryCacheImageInputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ImageWriteParam(javax.imageio.ImageWriteParam) Document(org.w3c.dom.Document) BufferedImage(java.awt.image.BufferedImage) ImageTypeSpecifier(javax.imageio.ImageTypeSpecifier) StreamSource(javax.xml.transform.stream.StreamSource) Source(javax.xml.transform.Source) IIOImage(javax.imageio.IIOImage) MemoryCacheImageOutputStream(javax.imageio.stream.MemoryCacheImageOutputStream) IIOMetadata(javax.imageio.metadata.IIOMetadata) ByteArrayInputStream(java.io.ByteArrayInputStream) StringReader(java.io.StringReader) ImageReader(javax.imageio.ImageReader) ImageOutputStream(javax.imageio.stream.ImageOutputStream) MemoryCacheImageOutputStream(javax.imageio.stream.MemoryCacheImageOutputStream)

Example 17 with IIOMetadata

use of javax.imageio.metadata.IIOMetadata in project jdk8u_jdk by JetBrains.

the class UserPluginMetadataFormatTest method doTest.

public void doTest() throws IOException {
    DummyImageReaderImpl reader;
    reader = new DummyImageReaderImpl(new DummyImageReaderSpiImpl());
    byte[] data = new byte[1024];
    ByteArrayInputStream bais = new ByteArrayInputStream(data);
    reader.setInput(ImageIO.createImageInputStream(bais));
    IIOMetadata metadata = reader.getImageMetadata(1);
    if (metadata == null) {
        throw new RuntimeException("IIOMetada is NULL");
    }
    String[] formatNames = metadata.getMetadataFormatNames();
    for (int j = 0; j < formatNames.length; j++) {
        String formatName = formatNames[j];
        System.out.println("\nFormat Names : " + formatName);
        try {
            IIOMetadataFormat metadataFormat = metadata.getMetadataFormat(formatName);
            System.out.println("  Class Name " + metadataFormat.getClass());
        } catch (IllegalStateException ise) {
            Throwable t = ise;
            t.printStackTrace();
            while (t.getCause() != null) {
                t = t.getCause();
                t.printStackTrace();
            }
            // test failed!
            // stop applet!
            System.out.println("Test faied.");
            throw new RuntimeException("Test failed.", ise);
        }
    }
}
Also used : IIOMetadata(javax.imageio.metadata.IIOMetadata) IIOMetadataFormat(javax.imageio.metadata.IIOMetadataFormat) ByteArrayInputStream(java.io.ByteArrayInputStream)

Example 18 with IIOMetadata

use of javax.imageio.metadata.IIOMetadata in project ChatGameFontificator by GlitchCog.

the class ControlWindow method saveScreenshot.

/**
     * Takes and saves a screenshot of the current chat window
     * 
     * @return whether the screenshot was saved
     */
private boolean saveScreenshot() {
    // Take the screenshot before the save file chooser is shown
    ChatPanel chat = chatWindow.getChatPanel();
    BufferedImage chatImage = new BufferedImage(chat.getWidth(), chat.getHeight(), screenshotOptions.isTransparencyEnabled() ? BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_INT_RGB);
    Graphics chatGraphics = chatImage.getGraphics();
    chat.paint(chatGraphics);
    final boolean chromaEnabled = Boolean.toString(true).equalsIgnoreCase(fProps.getProperty(FontificatorProperties.KEY_CHAT_CHROMA_ENABLED));
    if (screenshotOptions.isTransparencyEnabled() && chromaEnabled) {
        final int chromaKey = new Color(Integer.parseInt(fProps.getProperty(FontificatorProperties.KEY_COLOR_CHROMA_KEY), 16)).getRGB();
        final int transparentPixel = new Color(0, true).getRGB();
        for (int r = 0; r < chatImage.getHeight(); r++) {
            for (int c = 0; c < chatImage.getWidth(); c++) {
                if (chatImage.getRGB(c, r) == chromaKey) {
                    chatImage.setRGB(c, r, transparentPixel);
                }
            }
        }
    }
    File saveFile = getTargetSaveFile(screenshotSaver, DEFAULT_SCREENSHOT_FILE_EXTENSION);
    if (saveFile != null) {
        try {
            if (screenshotOptions.isMetadataEnabled()) {
                ImageWriter writer = ImageIO.getImageWritersByFormatName("PNG").next();
                ImageOutputStream stream = ImageIO.createImageOutputStream(saveFile);
                writer.setOutput(stream);
                IIOMetadata metadata = writer.getDefaultImageMetadata(ImageTypeSpecifier.createFromRenderedImage(chatImage), writer.getDefaultWriteParam());
                IIOMetadataNode title = generateMetadataNode("Title", "CGF Screenshot");
                IIOMetadataNode software = generateMetadataNode("Software", "Chat Game Fontificator");
                final String fontGameName = ControlPanelFont.getFontGameName(fProps.getProperty(FontificatorProperties.KEY_FONT_FILE_FONT));
                final String borderGameName = ControlPanelFont.getBorderGameName(fProps.getProperty(FontificatorProperties.KEY_FONT_FILE_BORDER));
                IIOMetadataNode description = generateMetadataNode("Description", fontGameName + " Font / " + borderGameName + " Border");
                IIOMetadataNode text = new IIOMetadataNode("tEXt");
                text.appendChild(title);
                text.appendChild(software);
                text.appendChild(description);
                final String metadataFormatStr = "javax_imageio_png_1.0";
                IIOMetadataNode root = new IIOMetadataNode(metadataFormatStr);
                root.appendChild(text);
                metadata.mergeTree(metadataFormatStr, root);
                writer.write(metadata, new IIOImage(chatImage, null, metadata), writer.getDefaultWriteParam());
                stream.close();
            } else {
                ImageIO.write(chatImage, "png", saveFile);
            }
            return true;
        } catch (Exception e) {
            logger.error("Unable to save screenshot", e);
            return false;
        }
    }
    return false;
}
Also used : Color(java.awt.Color) ImageWriter(javax.imageio.ImageWriter) ChatPanel(com.glitchcog.fontificator.gui.chat.ChatPanel) BufferedImage(java.awt.image.BufferedImage) IOException(java.io.IOException) IIOImage(javax.imageio.IIOImage) Graphics(java.awt.Graphics) IIOMetadata(javax.imageio.metadata.IIOMetadata) File(java.io.File) IIOMetadataNode(javax.imageio.metadata.IIOMetadataNode) ImageOutputStream(javax.imageio.stream.ImageOutputStream)

Example 19 with IIOMetadata

use of javax.imageio.metadata.IIOMetadata in project ChatGameFontificator by GlitchCog.

the class AnimatedGifUtil method loadDittoAnimatedGif.

/**
     * Fix (ditto) for Java's animated GIF interpretation
     * 
     * Adapted from http://stackoverflow.com/questions/26801433/fix-frame-rate-of-animated-gif-in-java#answer-26829534
     * 
     * @param url
     *            The URL for the animated GIF to be loaded
     * @param dim
     *            The dimension object to be filled by the width and height of the loaded animated GIF
     * @return The loaded animated GIF
     * @throws Exception
     */
public static Image loadDittoAnimatedGif(final URL url, Dimension dim) {
    final Image dimImage = new ImageIcon(url).getImage();
    Image image = null;
    try {
        ImageReader gifReader = ImageIO.getImageReadersByFormatName(GIF_EXTENSION).next();
        InputStream imageStream = url.openStream();
        gifReader.setInput(ImageIO.createImageInputStream(imageStream));
        IIOMetadata imageMetaData = gifReader.getImageMetadata(0);
        String metaFormatName = imageMetaData.getNativeMetadataFormatName();
        final int frameCount = gifReader.getNumImages(true);
        ByteArrayOutputStream baoStream = new ByteArrayOutputStream();
        ImageOutputStream ios = ImageIO.createImageOutputStream(baoStream);
        ImageWriter writer = ImageIO.getImageWriter(gifReader);
        writer.setOutput(ios);
        writer.prepareWriteSequence(null);
        final int imgWidth = dimImage.getWidth(null);
        final int imgHeight = dimImage.getHeight(null);
        dim.setSize(imgWidth, imgHeight);
        for (int i = 0; i < frameCount; i++) {
            // This read method takes into account the frame's top and left coordinates
            BufferedImage frame = gifReader.read(i);
            IIOMetadataNode nodes = (IIOMetadataNode) gifReader.getImageMetadata(i).getAsTree(metaFormatName);
            for (int j = 0; j < nodes.getLength(); j++) {
                IIOMetadataNode node = (IIOMetadataNode) nodes.item(j);
                if (GRAPHIC_CTRL_EXT.equalsIgnoreCase(node.getNodeName())) {
                    int delay = Integer.parseInt(node.getAttribute(ATTRIBUTE_DELAY_TIME));
                    // Minimum delay for browsers, which delay animated GIFs much more than would be to spec
                    if (delay < MIN_ANI_GIF_DELAY) {
                        node.setAttribute(ATTRIBUTE_DELAY_TIME, Integer.toString(MIN_ANI_GIF_DELAY));
                    }
                    // at least not for BTTV's (ditto)
                    if (node.getAttribute(ATTRIBUTE_DISPOSAL_METHOD).equals(DISPOSE_RESTORE_TO_PREVIOUS)) {
                        node.setAttribute(ATTRIBUTE_DISPOSAL_METHOD, DISPOSE_RESTORE_TO_BGCOLOR);
                    }
                }
            }
            IIOMetadata metadata = writer.getDefaultImageMetadata(new ImageTypeSpecifier(frame), null);
            metadata.setFromTree(metadata.getNativeMetadataFormatName(), nodes);
            // This modified frame is necessary to get the correct image placement, width, and height in the final GIF
            BufferedImage frameMod = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_ARGB);
            Graphics big = frameMod.getGraphics();
            big.drawImage(frame, 0, 0, null);
            IIOImage fixedFrame = new IIOImage(frameMod, null, metadata);
            writer.writeToSequence(fixedFrame, writer.getDefaultWriteParam());
        }
        writer.endWriteSequence();
        if (ios != null) {
            ios.close();
        }
        image = Toolkit.getDefaultToolkit().createImage(baoStream.toByteArray());
    } catch (Exception e) {
        // If anything goes wrong, just load it normally
        logger.error("Error loading animated GIF (ditto) from " + url, e);
        image = new ImageIcon(url).getImage();
        dim.setSize(image.getWidth(null), image.getHeight(null));
    }
    return image;
}
Also used : ImageIcon(javax.swing.ImageIcon) InputStream(java.io.InputStream) ImageWriter(javax.imageio.ImageWriter) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IIOImage(javax.imageio.IIOImage) Image(java.awt.Image) BufferedImage(java.awt.image.BufferedImage) BufferedImage(java.awt.image.BufferedImage) ImageTypeSpecifier(javax.imageio.ImageTypeSpecifier) IIOImage(javax.imageio.IIOImage) IIOMetadata(javax.imageio.metadata.IIOMetadata) Graphics(java.awt.Graphics) ImageReader(javax.imageio.ImageReader) IIOMetadataNode(javax.imageio.metadata.IIOMetadataNode) ImageOutputStream(javax.imageio.stream.ImageOutputStream)

Example 20 with IIOMetadata

use of javax.imageio.metadata.IIOMetadata in project jdk8u_jdk by JetBrains.

the class ImageReader method readAll.

/**
     * Returns an <code>Iterator</code> containing all the images,
     * thumbnails, and metadata, starting at the index given by
     * <code>getMinIndex</code>, from the input source in the form of
     * <code>IIOImage</code> objects.  An <code>Iterator</code>
     * containing <code>ImageReadParam</code> objects is supplied; one
     * element is consumed for each image read from the input source
     * until no more images are available.  If the read param
     * <code>Iterator</code> runs out of elements, but there are still
     * more images available from the input source, default read
     * params are used for the remaining images.
     *
     * <p> If <code>params</code> is <code>null</code>, a default read
     * param will be used for all images.
     *
     * <p> The actual <code>BufferedImage</code> referenced by the
     * returned <code>IIOImage</code> will be chosen using the
     * algorithm defined by the <code>getDestination</code> method.
     *
     * <p> Any registered <code>IIOReadProgressListener</code> objects
     * will be notified by calling their <code>sequenceStarted</code>
     * method once.  Then, for each image decoded, there will be a
     * call to <code>imageStarted</code>, followed by calls to
     * <code>imageProgress</code> as the read progresses, and finally
     * to <code>imageComplete</code>.  The
     * <code>sequenceComplete</code> method will be called after the
     * last image has been decoded.
     * <code>IIOReadUpdateListener</code> objects may be updated at
     * other times during the read as pixels are decoded.  Finally,
     * <code>IIOReadWarningListener</code> objects will receive
     * notification of any non-fatal warnings that occur during
     * decoding.
     *
     * <p> The set of source bands to be read and destination bands to
     * be written is determined by calling <code>getSourceBands</code>
     * and <code>getDestinationBands</code> on the supplied
     * <code>ImageReadParam</code>.  If the lengths of the arrays
     * returned by these methods differ, the set of source bands
     * contains an index larger that the largest available source
     * index, or the set of destination bands contains an index larger
     * than the largest legal destination index, an
     * <code>IllegalArgumentException</code> is thrown.
     *
     * <p> Thumbnails will be returned in their entirety regardless of the
     * region settings.
     *
     * <p> If any of the supplied <code>ImageReadParam</code>s contain
     * optional setting values not supported by this reader (<i>e.g.</i>
     * source render size or any format-specific settings), they will
     * be ignored.
     *
     * @param params an <code>Iterator</code> containing
     * <code>ImageReadParam</code> objects.
     *
     * @return an <code>Iterator</code> representing the
     * contents of the input source as <code>IIOImage</code>s.
     *
     * @exception IllegalStateException if the input source has not been
     * set.
     * @exception IllegalArgumentException if any
     * non-<code>null</code> element of <code>params</code> is not an
     * <code>ImageReadParam</code>.
     * @exception IllegalArgumentException if the set of source and
     * destination bands specified by
     * <code>param.getSourceBands</code> and
     * <code>param.getDestinationBands</code> differ in length or
     * include indices that are out of bounds.
     * @exception IllegalArgumentException if a resulting image would
     * have a width or height less than 1.
     * @exception IOException if an error occurs during reading.
     *
     * @see ImageReadParam
     * @see IIOImage
     */
public Iterator<IIOImage> readAll(Iterator<? extends ImageReadParam> params) throws IOException {
    List output = new ArrayList();
    int imageIndex = getMinIndex();
    // Inform IIOReadProgressListeners we're starting a sequence
    processSequenceStarted(imageIndex);
    while (true) {
        // Inform IIOReadProgressListeners and IIOReadUpdateListeners
        // that we're starting a new image
        ImageReadParam param = null;
        if (params != null && params.hasNext()) {
            Object o = params.next();
            if (o != null) {
                if (o instanceof ImageReadParam) {
                    param = (ImageReadParam) o;
                } else {
                    throw new IllegalArgumentException("Non-ImageReadParam supplied as part of params!");
                }
            }
        }
        BufferedImage bi = null;
        try {
            bi = read(imageIndex, param);
        } catch (IndexOutOfBoundsException e) {
            break;
        }
        ArrayList thumbnails = null;
        int numThumbnails = getNumThumbnails(imageIndex);
        if (numThumbnails > 0) {
            thumbnails = new ArrayList();
            for (int j = 0; j < numThumbnails; j++) {
                thumbnails.add(readThumbnail(imageIndex, j));
            }
        }
        IIOMetadata metadata = getImageMetadata(imageIndex);
        IIOImage im = new IIOImage(bi, thumbnails, metadata);
        output.add(im);
        ++imageIndex;
    }
    // Inform IIOReadProgressListeners we're ending a sequence
    processSequenceComplete();
    return output.iterator();
}
Also used : IIOMetadata(javax.imageio.metadata.IIOMetadata) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) Point(java.awt.Point) BufferedImage(java.awt.image.BufferedImage)

Aggregations

IIOMetadata (javax.imageio.metadata.IIOMetadata)37 BufferedImage (java.awt.image.BufferedImage)20 ImageTypeSpecifier (javax.imageio.ImageTypeSpecifier)20 ImageWriter (javax.imageio.ImageWriter)18 IIOImage (javax.imageio.IIOImage)17 ImageOutputStream (javax.imageio.stream.ImageOutputStream)15 ImageWriteParam (javax.imageio.ImageWriteParam)14 ByteArrayOutputStream (java.io.ByteArrayOutputStream)10 ByteArrayInputStream (java.io.ByteArrayInputStream)9 ImageReader (javax.imageio.ImageReader)9 File (java.io.File)8 IOException (java.io.IOException)7 Node (org.w3c.dom.Node)7 Rectangle (java.awt.Rectangle)5 ImageInputStream (javax.imageio.stream.ImageInputStream)5 FileOutputStream (java.io.FileOutputStream)4 IIOMetadataNode (javax.imageio.metadata.IIOMetadataNode)4 Graphics (java.awt.Graphics)3 Point (java.awt.Point)3 ColorModel (java.awt.image.ColorModel)3