Example usage for javax.imageio.metadata IIOMetadata getAsTree

List of usage examples for javax.imageio.metadata IIOMetadata getAsTree

Introduction

In this page you can find the example usage for javax.imageio.metadata IIOMetadata getAsTree.

Prototype

public abstract Node getAsTree(String formatName);

Source Link

Document

Returns an XML DOM Node object that represents the root of a tree of metadata contained within this object according to the conventions defined by a given metadata format.

Usage

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

private static Document parse(InputStream source, Element instruction, PrintWriter logger) throws Exception {
    ImageReader reader;/* ww  w . j  ava2 s  .c o  m*/
    try {
        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: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 .co 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.apache.pdfbox.tools.imageio.TestImageIOUtils.java

/**
 * checks whether the compression of a TIFF file is as expected.
 *
 * @param filename Filename/*ww  w  .j  a  va  2s. c  o  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.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  w  ww  .  java  2 s . com
 * @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:com.qwazr.extractor.parser.ImageParser.java

@Override
public void parseContent(final MultivaluedMap<String, String> parameters, final Path path,
        final String extension, final String mimeType, final ParserResultBuilder resultBuilder)
        throws Exception {

    final ImagePHash imgPhash = new ImagePHash();
    try (final ImageInputStream in = ImageIO.createImageInputStream(path.toFile())) {
        final Iterator<ImageReader> readers = ImageIO.getImageReaders(in);
        if (readers.hasNext()) {
            ParserFieldsBuilder result = resultBuilder.newDocument();
            ImageReader reader = readers.next();
            resultBuilder.metas().set(MIME_TYPE, "image/" + reader.getFormatName().toLowerCase());
            try {
                reader.setInput(in);/*from  w w w .j av  a 2s . c o  m*/
                result.add(WIDTH, reader.getWidth(0));
                result.add(HEIGHT, reader.getHeight(0));
                result.add(FORMAT, reader.getFormatName());
                result.add(PHASH, imgPhash.getHash(reader.read(0)));
                IIOMetadata metadata = reader.getImageMetadata(0);
                if (metadata != null) {
                    String[] names = metadata.getMetadataFormatNames();
                    if (names != null)
                        for (String name : names)
                            browseNodes("META", metadata.getAsTree(name), result);
                }
            } finally {
                reader.dispose();
            }
        }
    }
}

From source file:net.d53dev.dslfy.web.service.GifService.java

private void configureGIFFrame(IIOMetadata meta, String delayTime, int imageIndex, String disposalMethod,
        int loopCount) {
    String metaFormat = meta.getNativeMetadataFormatName();

    if (!"javax_imageio_gif_image_1.0".equals(metaFormat)) {
        throw new IllegalArgumentException("Unfamiliar gif metadata format: " + metaFormat);
    }/*w w w. j a  v  a2 s.  c  om*/

    Node root = meta.getAsTree(metaFormat);

    Node child = root.getFirstChild();
    while (child != null) {
        if ("GraphicControlExtension".equals(child.getNodeName()))
            break;
        child = child.getNextSibling();
    }

    IIOMetadataNode gce = (IIOMetadataNode) child;
    gce.setAttribute("userDelay", "FALSE");
    gce.setAttribute("delayTime", delayTime);
    gce.setAttribute("disposalMethod", disposalMethod);

    if (imageIndex == 0) {
        IIOMetadataNode aes = new IIOMetadataNode("ApplicationExtensions");
        IIOMetadataNode ae = new IIOMetadataNode("ApplicationExtension");
        ae.setAttribute("applicationID", "NETSCAPE");
        ae.setAttribute("authenticationCode", "2.0");
        byte[] uo = new byte[] { 0x1, (byte) (loopCount & 0xFF), (byte) ((loopCount >> 8) & 0xFF) };
        ae.setUserObject(uo);
        aes.appendChild(ae);
        root.appendChild(aes);
    }

    try {
        meta.setFromTree(metaFormat, root);
    } catch (IIOInvalidTreeException e) {
        throw new Error(e);
    }
}

From source file:org.apache.xmlgraphics.image.loader.impl.imageio.ImageLoaderImageIO.java

/**
 * Extract ICC Profile from ImageIO Metadata. This method currently only
 * supports PNG and JPEG metadata.//w  w  w  . j a  va2s  .co  m
 *
 * @param iiometa
 *            The ImageIO Metadata
 * @return an ICC Profile or null.
 */
private ICC_Profile tryToExctractICCProfile(IIOMetadata iiometa) {
    ICC_Profile iccProf = null;
    String supportedFormats[] = iiometa.getMetadataFormatNames();
    for (int i = 0; i < supportedFormats.length; i++) {
        String format = supportedFormats[i];
        Element root = (Element) iiometa.getAsTree(format);
        if (PNG_METADATA_NODE.equals(format)) {
            iccProf = this.tryToExctractICCProfileFromPNGMetadataNode(root);
        } else if (JPEG_METADATA_NODE.equals(format)) {
            iccProf = this.tryToExctractICCProfileFromJPEGMetadataNode(root);
        }
    }
    return iccProf;
}

From source file:net.algart.simagis.imageio.IIOMetadataToJsonConverter.java

public final JSONObject toJson(IIOMetadata metadata) throws JSONException {
    if (metadata == null)
        throw new NullPointerException("Null metadata");
    JSONObject result = new JSONObject();
    JSONArray formats = new JSONArray();
    final String[] formatNames = metadata.getMetadataFormatNames();
    if (formatNames != null) {
        for (String formatName : formatNames) {
            final Node tree = metadata.getAsTree(formatName);
            JSONObject format = new JSONObject();
            format.put("formatName", formatName);
            format.put("tree", treeToJson(tree));
            formats.put(format);/*from   w w  w.j  ava2 s .co  m*/
        }
    }
    result.put("formats", formats);
    return result;
}

From source file:org.photovault.imginfo.CreateCopyImageCommand.java

/**
 Helper function to save a rendered image to file
 @param instanceFile The file into which the image will be saved
 @param img Image that willb e saved//from w ww  .ja  va  2  s . c o  m
 @param xmpData XPM metadata packet that should be saved with the image
 @throws PhotovaultException if saving does not succeed
 */
protected void saveImage(File instanceFile, RenderedImage img, byte[] xmpData) throws PhotovaultException {
    ImageOutputStream out = null;
    log.debug("Entry: saveImage, file = " + instanceFile.getAbsolutePath());
    try {
        out = new FileImageOutputStream(instanceFile);
    } catch (IOException e) {
        log.error("Error writing image: " + e.getMessage());
        throw new PhotovaultException(e.getMessage());
    }
    if (img.getSampleModel().getSampleSize(0) == 16) {
        log.debug("16 bit image, converting to 8 bits");
        double[] subtract = new double[1];
        subtract[0] = 0;
        double[] divide = new double[1];
        divide[0] = 1. / 256.;
        // Now we can rescale the pixels gray levels:
        ParameterBlock pbRescale = new ParameterBlock();
        pbRescale.add(divide);
        pbRescale.add(subtract);
        pbRescale.addSource(img);
        PlanarImage outputImage = (PlanarImage) JAI.create("rescale", pbRescale, null);
        // Make sure it is a byte image - force conversion.
        ParameterBlock pbConvert = new ParameterBlock();
        pbConvert.addSource(outputImage);
        pbConvert.add(DataBuffer.TYPE_BYTE);
        img = JAI.create("format", pbConvert);
    }

    IIOImage iioimg = new IIOImage(img, null, null);

    /*
     Not all encoders support metadata handling
     */
    Iterator writers = ImageIO.getImageWritersByFormatName("jpeg");
    ImageWriter imgwriter = null;
    while (writers.hasNext()) {
        imgwriter = (ImageWriter) writers.next();
        if (imgwriter.getClass().getName().endsWith("JPEGImageEncoder")) {
            // Break on finding the core provider.
            break;
        }
    }
    if (imgwriter == null) {
        System.err.println("Cannot find core JPEG writer!");
    }
    imgwriter.addIIOWriteWarningListener(new IIOWriteWarningListener() {

        public void warningOccurred(ImageWriter arg0, int arg1, String arg2) {
            log.warn("Warning from ImageWriter: " + arg2);
        }
    });
    ImageWriteParam params = imgwriter.getDefaultWriteParam();
    ImageTypeSpecifier its = ImageTypeSpecifier.createFromRenderedImage(img);
    IIOMetadata metadata = imgwriter.getDefaultImageMetadata(its, null);

    IIOMetadataNode metatop = (IIOMetadataNode) metadata.getAsTree("javax_imageio_jpeg_image_1.0");
    NodeList markerSeqNodes = metatop.getElementsByTagName("markerSequence");
    if (markerSeqNodes.getLength() > 0) {
        IIOMetadataNode xmpNode = new IIOMetadataNode("unknown");
        xmpNode.setAttribute("MarkerTag", "225");
        xmpNode.setUserObject(xmpData);
        markerSeqNodes.item(0).appendChild(xmpNode);
    }

    try {
        metadata.setFromTree("javax_imageio_jpeg_image_1.0", metatop);
    } catch (Exception e) {
        log.warn("error editing metadata: " + e.getMessage());
        e.printStackTrace();
        throw new PhotovaultException("error setting image metadata: \n" + e.getMessage());
    }

    iioimg.setMetadata(metadata);

    try {
        imgwriter.setOutput(out);
        imgwriter.write(iioimg);
    } catch (IOException e) {
        log.warn("Exception while encoding" + e.getMessage());
        throw new PhotovaultException(
                "Error writing instance " + instanceFile.getAbsolutePath() + ": " + e.getMessage());
    } finally {
        try {
            out.close();
        } catch (IOException e) {
            log.warn("Exception while closing file: " + e.getMessage());
            imgwriter.dispose();
            throw new PhotovaultException(
                    "Error writing instance " + instanceFile.getAbsolutePath() + ": " + e.getMessage());

        }
        imgwriter.dispose();
    }
    log.debug("Exit: saveImage");
}

From source file:org.photovault.image.ImageIOImage.java

private void readImageMetadata(ImageReader reader) throws IOException {
    Set<String> nodes = new HashSet<String>();
    nodes.add("unknown");
    IIOMetadata iioMetadata = reader.getImageMetadata(0, "javax_imageio_jpeg_image_1.0", nodes);
    if (iioMetadata != null) {
        Node tree = iioMetadata.getAsTree("javax_imageio_jpeg_image_1.0");
        log.debug("read metadata: " + iioMetadata.toString());
        this.parseJPEGMetadata((IIOMetadataNode) tree);
    }// w  w w  .j a v a  2  s  . c om
}