Example usage for javax.imageio.metadata IIOMetadata getNativeMetadataFormatName

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

Introduction

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

Prototype

public String getNativeMetadataFormatName() 

Source Link

Document

Returns the name of the "native" metadata format for this plug-in, which typically allows for lossless encoding and transmission of the metadata stored in the format handled by this plug-in.

Usage

From source file:com.aegon.pdf2tiff.TIFFUtil.java

/**
 * Updates the given ImageIO metadata with Sun's custom TIFF tags.
 * {@see https://svn.apache.org/repos/asf/xmlgraphics/commons/tags/commons-1_3_1/src/java/org/
 *       apache/xmlgraphics/image/writer/imageio/ImageIOTIFFImageWriter.java}
 * {@see http://download.java.net/media/jai-imageio/javadoc/1.0_01/com/sun/media/imageio/
 *       plugins/tiff/package-summary.html}
 * {@see http://partners.adobe.com/public/developer/tiff/index.html}
 * @param image buffered image which will be written
 * @param metadata ImageIO metadata/*from   ww w  .  ja v  a  2s .  co  m*/
 * @param dpi image dots per inch
 */
public static void updateMetadata(IIOMetadata metadata, BufferedImage image, int dpi) {
    debugLogMetadata(metadata, SUN_TIFF_FORMAT);

    if (!SUN_TIFF_FORMAT.equals(metadata.getNativeMetadataFormatName())) {
        LOG.debug("Using unknown TIFF image writer: " + metadata.getNativeMetadataFormatName());
        return;
    }

    IIOMetadataNode root = new IIOMetadataNode(SUN_TIFF_FORMAT);
    IIOMetadataNode ifd;
    if (root.getElementsByTagName("TIFFIFD").getLength() == 0) {
        ifd = new IIOMetadataNode("TIFFIFD");
        ifd.setAttribute("tagSets", "com.sun.media.imageio.plugins.tiff.BaselineTIFFTagSet");
        root.appendChild(ifd);
    } else {
        ifd = (IIOMetadataNode) root.getElementsByTagName("TIFFIFD").item(0);
    }

    // standard metadata does not work, so we set the DPI manually
    ifd.appendChild(createRationalField(282, "XResolution", dpi, 1));
    ifd.appendChild(createRationalField(283, "YResolution", dpi, 1));
    ifd.appendChild(createShortField(296, "ResolutionUnit", 2)); // Inch

    ifd.appendChild(createLongField(278, "RowsPerStrip", image.getHeight()));
    ifd.appendChild(createAsciiField(305, "Software", "PDFBOX"));

    if (image.getType() == BufferedImage.TYPE_BYTE_BINARY && image.getColorModel().getPixelSize() == 1) {
        // set PhotometricInterpretation WhiteIsZero
        // because of bug in Windows XP preview
        ifd.appendChild(createShortField(262, "PhotometricInterpretation", 0));
    }

    try {
        metadata.mergeTree(SUN_TIFF_FORMAT, root);
    } catch (IIOInvalidTreeException e) {
        // should never happen
        throw new RuntimeException(e);
    }

    debugLogMetadata(metadata, SUN_TIFF_FORMAT);
}

From source file:com.ackpdfbox.app.imageio.TIFFUtil.java

/**
 * Updates the given ImageIO metadata with Sun's custom TIFF tags, as described in
 * the <a href="https://svn.apache.org/repos/asf/xmlgraphics/commons/tags/commons-1_3_1/src/java/org/apache/xmlgraphics/image/writer/imageio/ImageIOTIFFImageWriter.java">org.apache.xmlgraphics.image.writer.ImageIOTIFFImageWriter
 * sources</a>, /*from   w ww  . j  a  v  a2  s.  co  m*/
 * the <a href="http://download.java.net/media/jai-imageio/javadoc/1.0_01/com/sun/media/imageio/plugins/tiff/package-summary.html">com.sun.media.imageio.plugins.tiff
 * package javadoc</a>
 * and the <a href="http://partners.adobe.com/public/developer/tiff/index.html">TIFF
 * specification</a>.
 *
 * @param image buffered image which will be written
 * @param metadata ImageIO metadata
 * @param dpi image dots per inch
 * @throws IIOInvalidTreeException if something goes wrong
 */
static void updateMetadata(IIOMetadata metadata, BufferedImage image, int dpi) throws IIOInvalidTreeException {
    debugLogMetadata(metadata, SUN_TIFF_FORMAT);

    if (!SUN_TIFF_FORMAT.equals(metadata.getNativeMetadataFormatName())) {
        LOG.debug("Using unknown TIFF image writer: " + metadata.getNativeMetadataFormatName());
        return;
    }

    IIOMetadataNode root = new IIOMetadataNode(SUN_TIFF_FORMAT);
    IIOMetadataNode ifd;
    if (root.getElementsByTagName("TIFFIFD").getLength() == 0) {
        ifd = new IIOMetadataNode("TIFFIFD");
        ifd.setAttribute("tagSets", tagSetClassName);
        root.appendChild(ifd);
    } else {
        ifd = (IIOMetadataNode) root.getElementsByTagName("TIFFIFD").item(0);
    }

    // standard metadata does not work, so we set the DPI manually
    ifd.appendChild(createRationalField(282, "XResolution", dpi, 1));
    ifd.appendChild(createRationalField(283, "YResolution", dpi, 1));
    ifd.appendChild(createShortField(296, "ResolutionUnit", 2)); // Inch

    ifd.appendChild(createLongField(278, "RowsPerStrip", image.getHeight()));
    ifd.appendChild(createAsciiField(305, "Software", "PDFBOX"));

    if (image.getType() == BufferedImage.TYPE_BYTE_BINARY && image.getColorModel().getPixelSize() == 1) {
        // set PhotometricInterpretation WhiteIsZero
        // because of bug in Windows XP preview
        ifd.appendChild(createShortField(262, "PhotometricInterpretation", 0));
    }

    metadata.mergeTree(SUN_TIFF_FORMAT, root);

    debugLogMetadata(metadata, SUN_TIFF_FORMAT);
}

From source file:com.sketchy.utils.image.SketchyImage.java

public static SketchyImage load(File file) throws Exception {
    SketchyImage sketchyImage = null;//from w  ww . j  a v a2  s  .c o m

    if (!file.exists() || !file.canRead()) {
        throw new Exception("Can not find or read File: " + file.getPath() + "!");
    }

    if (!StringUtils.endsWithIgnoreCase(file.getName(), ".png")) {
        throw new Exception("Can not load SketchyImage! Must be a .png file!");
    }

    Iterator<ImageReader> imageReaders = ImageIO.getImageReadersByFormatName("png");
    ImageReader imageReader = null;
    if (imageReaders.hasNext()) { // Just get first one
        imageReader = imageReaders.next();
    }
    if (imageReader == null) {
        // this should never happen!! if so.. we got problems
        throw new Exception("Can not find ImageReader for .png Files!");
    }

    ImageInputStream is = null;
    try {
        is = ImageIO.createImageInputStream(file);
        imageReader.setInput(is, true);
        IIOMetadata metaData = imageReader.getImageMetadata(0); // always get first image
        IIOMetadataNode metaDataNode = (IIOMetadataNode) metaData
                .getAsTree(metaData.getNativeMetadataFormatName());
        if (metaDataNode == null) {
            throw new Exception("Error retreiving MetaData properties from .png File!");
        }

        NodeList childNodes = metaDataNode.getElementsByTagName("pHYs");
        // only look in the first node
        if (childNodes.getLength() == 0) {
            throw new Exception("Invalid SketchyImage file. It must contain 'pixelsPerUnit' MetaData!");
        }
        IIOMetadataNode physNode = (IIOMetadataNode) childNodes.item(0);
        String pixelsPerUnitXAxisAttribute = physNode.getAttribute("pixelsPerUnitXAxis");
        String pixelsPerUnitYAxisAttribute = physNode.getAttribute("pixelsPerUnitYAxis");
        // String unitSpecifierAttribute = physNode.getAttribute("unitSpecifier"); Just assuming meter
        if (StringUtils.isBlank(pixelsPerUnitXAxisAttribute)) {
            throw new Exception("Invalid SketchyImage file. It must contain 'pixelsPerUnitXAxis' MetaData!");
        }
        if (StringUtils.isBlank(pixelsPerUnitYAxisAttribute)) {
            throw new Exception("Invalid SketchyImage file. It must contain 'pixelsPerUnitYAxis' MetaData!");
        }

        int pixelsPerUnitXAxis;
        try {
            pixelsPerUnitXAxis = Integer.parseInt(pixelsPerUnitXAxisAttribute);
            if (pixelsPerUnitXAxis <= 0)
                throw new Exception("Value must be > 0");
        } catch (Exception e) {
            throw new Exception("Invalid 'pixelsPerUnitXAxis' MetaData Attribute! " + e.getMessage());
        }

        int pixelsPerUnitYAxis;
        try {
            pixelsPerUnitYAxis = Integer.parseInt(pixelsPerUnitYAxisAttribute);
            if (pixelsPerUnitYAxis <= 0)
                throw new Exception("Value must be > 0");
        } catch (Exception e) {
            throw new Exception("Invalid 'pixelsPerUnitYAxis' MetaData Attribute! " + e.getMessage());
        }

        // We successfully processed the MetaData.. now read/set the image 
        BufferedImage bufferedImage = imageReader.read(0); // always get first image

        double xPixelsPerMM = pixelsPerUnitXAxis / 1000.0;
        double yPixelsPerMM = pixelsPerUnitYAxis / 1000.0;

        sketchyImage = new SketchyImage(bufferedImage, xPixelsPerMM, yPixelsPerMM);
    } catch (Exception e) {
        throw new Exception("Error Loading SketchyImage File: " + file.getPath() + "! " + e.getMessage());
    } finally {
        IOUtils.closeQuietly(is);
    }

    return sketchyImage;
}

From source file:com.sketchy.utils.image.SketchyImage.java

public static void save(SketchyImage sketchyImage, File file) throws Exception {
    if (!file.getParentFile().canWrite()) {
        throw new Exception("Can not write to File: " + file.getPath() + "!");
    }//from   w  ww  . j av a 2  s  . c o  m

    if (!StringUtils.endsWithIgnoreCase(file.getName(), ".png")) {
        throw new Exception("Can not save SketchyImage! Must be a .png file!");
    }

    Iterator<ImageWriter> imageWriters = ImageIO.getImageWritersByFormatName("png");
    ImageWriter imageWriter = null;
    if (imageWriters.hasNext()) { // Just get first one
        imageWriter = imageWriters.next();
    }
    if (imageWriter == null) {
        // this should never happen!! if so.. we got problems
        throw new Exception("Can not find ImageReader for .png Files!");
    }

    ImageOutputStream os = null;
    try {
        os = ImageIO.createImageOutputStream(file);
        imageWriter.setOutput(os);

        ImageWriteParam imageWriterParam = imageWriter.getDefaultWriteParam();
        IIOMetadata metadata = imageWriter.getDefaultImageMetadata(
                ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_BYTE_BINARY),
                imageWriterParam);

        String metaDataFormatName = metadata.getNativeMetadataFormatName();
        IIOMetadataNode metaDataNode = (IIOMetadataNode) metadata.getAsTree(metaDataFormatName);

        NodeList childNodes = metaDataNode.getElementsByTagName("pHYs");
        IIOMetadataNode physNode = null;
        if (childNodes.getLength() == 0) {
            physNode = new IIOMetadataNode("pHYs");
            physNode.setAttribute("pixelsPerUnitXAxis",
                    Integer.toString((int) Math.ceil(sketchyImage.dotsPerMillimeterWidth * 1000)));
            physNode.setAttribute("pixelsPerUnitYAxis",
                    Integer.toString((int) Math.ceil(sketchyImage.dotsPerMillimeterHeight * 1000)));
            physNode.setAttribute("unitSpecifier", "meter"); // always meter
            metaDataNode.appendChild(physNode);
        } else {
            for (int nodeIdx = 0; nodeIdx < childNodes.getLength(); nodeIdx++) {
                physNode = (IIOMetadataNode) childNodes.item(nodeIdx);
                physNode.setAttribute("pixelsPerUnitXAxis",
                        Integer.toString((int) Math.ceil(sketchyImage.dotsPerMillimeterWidth * 1000)));
                physNode.setAttribute("pixelsPerUnitYAxis",
                        Integer.toString((int) Math.ceil(sketchyImage.dotsPerMillimeterHeight * 1000)));
                physNode.setAttribute("unitSpecifier", "meter"); // always meter
                metaDataNode.appendChild(physNode);
            }
        }
        metadata.setFromTree(metaDataFormatName, metaDataNode);
        imageWriter.write(new IIOImage(sketchyImage.image, null, metadata));
        os.flush();
    } catch (Exception e) {
        throw new Exception("Error Saving SketchyImage File: " + file.getPath() + "!  " + e.getMessage());
    } finally {
        IOUtils.closeQuietly(os);
    }
}

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

private static Document parse(InputStream source, Element instruction, PrintWriter logger) throws Exception {
    ImageReader reader;//from   ww  w. j a  va2s. c  om
    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;
    }/*w  w  w  . j  av a2  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: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);
    }//from  ww w.j  av a2  s  .co  m

    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:de.unigoettingen.sub.commons.contentlib.imagelib.JpegInterpreter.java

private IIOMetadata getImageMetadata(ImageReader ir) throws ImageInterpreterException {
    IIOMetadata md = null;
    Node treeNode = null;//from  w ww.j  a  v a 2 s  . co m
    try {
        md = ir.getImageMetadata(0);
        String formatName = md.getNativeMetadataFormatName();
        treeNode = md.getAsTree(formatName);
    } catch (Error e) {
        throw new ImageInterpreterException("Error when attempting to parse image metadata: " + e.toString());
    } catch (Exception e) {
        throw new ImageInterpreterException("Error when attempting to parse image metadata: " + e.toString());
    }
    if ((treeNode == null) || (treeNode.getChildNodes() == null)) {
        throw new ImageInterpreterException("Image metadata Node is null or empty");
    }
    return md;
}

From source file:de.unigoettingen.sub.commons.contentlib.imagelib.JpegInterpreter.java

/************************************************************************************
 * Constructor for {@link JpegInterpreter} to read an jpeg image from given {@link InputStream}
 * /*from   w w  w  .j  a v a  2  s. co m*/
 * @param inStream {@link InputStream}
 * @throws ImageInterpreterException
 ************************************************************************************/
public JpegInterpreter(InputStream inStream) throws ImageInterpreterException {
    InputStream inputStream = null;
    byte imagebytes[] = null;

    // read the stream and store it in a byte array
    try {
        this.readImageStream(inStream);
        imagebytes = this.getImageByteStream();
        if (inStream != null) {
            inStream.close();
        }
    } catch (IOException e) {
        LOGGER.error("Failed to close input stream", e);
    }
    //

    // Read image bytes into new stream
    try {
        inputStream = new ByteArraySeekableStream(imagebytes);
    } catch (IOException e1) {
        LOGGER.error("Can't transform the image's byte array to stream");
        ImageInterpreterException iie = new ImageInterpreterException(
                "Can't transform the image's byte array to stream");
        throw iie;
    }
    //

    // read the stream
    Node domNode = null;
    try {
        IIOImage image = createImage(inputStream, 0);
        if ((image == null) || (image.getRenderedImage() == null)) {
            LOGGER.error("Failed to read image from input stream. Aborting!");
            ImageInterpreterException iie = new ImageInterpreterException(
                    "Failed to read image from input stream. Aborting!");
            throw iie;
        }
        this.renderedimage = image.getRenderedImage();
        IIOMetadata metadata = image.getMetadata();
        if (metadata != null) {
            String formatName = metadata.getNativeMetadataFormatName();
            domNode = metadata.getAsTree(formatName);
            if ((domNode == null) || (domNode.getChildNodes() == null)) {
                metadata = null;
            }
        }
        if (metadata == null) {
            LOGGER.error("Failed to read metadata from input stream. Using default values");
            xResolution = defaultXResolution;
            yResolution = defaultYResolution;
            width = this.renderedimage.getWidth();
            height = this.renderedimage.getHeight();
            samplesPerPixel = 1;
            return;
        }
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                LOGGER.error("Failed to close input stream");
            }
        }
    }
    //

    // get new metadata - this is not very sophisticated parsing the DOM
    // tree - needs to be replaced by
    // XPATH expressions - see above
    String height_str = this.getNumLines(domNode);
    if (height_str != null) {
        this.height = Integer.parseInt(height_str);
    }

    String width_str = this.getSamplesPerLine(domNode);
    if (width_str != null) {
        this.width = Integer.parseInt(width_str);
    }

    String resunits = this.getResUnits(domNode);
    int resunits_int = 1; // default is DPI
    // if resunits==1 than it is dpi,
    // if resunits==2 than it is dpcm
    if (resunits != null) {
        resunits_int = Integer.parseInt(resunits);
    }

    String xres_str = this.getXdensity(domNode);
    if (xres_str != null) {
        this.xResolution = Integer.parseInt(xres_str);
        if (resunits_int == 2) {
            this.xResolution = this.xResolution * 2.54f; // d/inch = d/cm * cm/inch
            // this.xResolution = this.xResolution / 2.54f;
        }
    }

    String yres_str = this.getYdensity(domNode);
    if (yres_str != null) {
        this.yResolution = Integer.parseInt(yres_str);
        if (resunits_int == 2) {
            this.yResolution = this.yResolution * 2.54f; // d/inch = d/cm * cm/inch
            // this.yResolution = this.yResolution / 2.54f;
        }
    }

    if ((resunits == null) || (resunits_int == 0) || (xResolution <= 1.0) || (yResolution <= 1.0)) {
        xResolution = defaultXResolution;
        yResolution = defaultYResolution;
    }

    String colordepth_str = this.getSamplePrecision(domNode);
    if (colordepth_str != null) {
        this.colorDepth = Integer.parseInt(colordepth_str);
    }

    String samplesperpixel_str = this.getNumFrames(domNode);
    if (samplesperpixel_str != null) {
        this.samplesPerPixel = Integer.parseInt(samplesperpixel_str);
    }
}