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

/************************************************************************************
 * set metadata to image/*from w w w .  ja  v  a2s.c  o m*/
 * 
 * @param iomd the given {@link IIOMetadata} to set
 ************************************************************************************/
private void setMetadata(IIOMetadata iomd) {

    Node node = iomd.getAsTree("javax_imageio_jpeg_image_1.0");

    // set dimensions
    setSamplesPerLine(node, this.getWidth());
    setNumLines(node, this.getHeight());

    // what are child nodes?
    NodeList nl = node.getChildNodes();
    for (int j = 0; j < nl.getLength(); j++) {
        Node n = nl.item(j);

        if (n.getNodeName().equals("JPEGvariety")) {
            NodeList childNodes = n.getChildNodes();

            for (int k = 0; k < childNodes.getLength(); k++) {
                if (childNodes.item(k).getNodeName().equals("app0JFIF")) {

                    // get the attributes resUnits, Xdensity, and Ydensity
                    Node resUnitsNode = getAttributeByName(childNodes.item(k), "resUnits");
                    Node XdensityNode = getAttributeByName(childNodes.item(k), "Xdensity");
                    Node YdensityNode = getAttributeByName(childNodes.item(k), "Ydensity");
                    // overwrite values for that node
                    resUnitsNode.setNodeValue("1"); // it's dpi

                    int xres = (int) this.getXResolution();
                    int yres = (int) this.getYResolution();
                    if (xres == 0) {
                        xres = defaultXResolution;
                    }
                    if (yres == 0) {
                        yres = defaultYResolution;
                    }
                    XdensityNode.setNodeValue(String.valueOf(xres));
                    YdensityNode.setNodeValue(String.valueOf(yres));

                } // endif
            } // end id
            break; // don't need to change the other children
        } // end id

    } // end for

    // set the XML tree for the IIOMetadata object
    try {
        iomd.setFromTree("javax_imageio_jpeg_image_1.0", node);
    } catch (IIOInvalidTreeException e) {
        LOGGER.error(e); // To change body of catch statement
    }

}

From source file:nl.softwaredesign.exporter.ODTExportFormat.java

/**
 * TODO Move to utility class?//from   w w w  . j a  v a  2s . com
 * Extract the content data (bytes) from the given image.
 * @param icon image to get bytes for
 * @param format desired format for image
 * @param background Color to use as background if transparency in image
 * @param width Desired width of the image in the byte array
 * @param height Desired width of the image in the byte array
 * @return the bytes of the image
 * @throws IOException
 */
private byte[] imageToBytes(ImageIcon icon, String format, Color background, int width, int height)
        throws IOException {
    Iterator writers = ImageIO.getImageWritersByFormatName(format);
    ImageWriter writer = (ImageWriter) writers.next();
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    ImageOutputStream ios = ImageIO.createImageOutputStream(output);
    writer.setOutput(ios);
    BufferedImage img;
    if ("png".equalsIgnoreCase(format) || "gif".equalsIgnoreCase(format)) {
        img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    } else {
        img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    }
    WaitingObserver observer = new WaitingObserver();
    if (!img.getGraphics().drawImage(icon.getImage(), 0, 0, width, height, background, observer)) {
        try {
            observer.waitForDone();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return new byte[0];
        }
    }
    IIOMetadata metadata = writer.getDefaultImageMetadata(new ImageTypeSpecifier(img),
            writer.getDefaultWriteParam());
    if (format.equalsIgnoreCase("jpg")) {
        Element tree = (Element) metadata.getAsTree("javax_imageio_jpeg_image_1.0");
        Element jfif = (Element) tree.getElementsByTagName("app0JFIF").item(0);
        jfif.setAttribute("Xdensity", Integer.toString(72));
        jfif.setAttribute("Ydensity", Integer.toString(72));
        jfif.setAttribute("resUnits", "1");
        metadata.setFromTree("javax_imageio_jpeg_image_1.0", tree);
    } else {
        double dotsPerMilli = 7.2 / 2.54;
        IIOMetadataNode horiz = new IIOMetadataNode("HorizontalPixelSize");
        horiz.setAttribute("value", Double.toString(dotsPerMilli));
        IIOMetadataNode vert = new IIOMetadataNode("VerticalPixelSize");
        vert.setAttribute("value", Double.toString(dotsPerMilli));
        IIOMetadataNode dim = new IIOMetadataNode("Dimension");
        dim.appendChild(horiz);
        dim.appendChild(vert);
        IIOMetadataNode root = new IIOMetadataNode("javax_imageio_1.0");
        root.appendChild(dim);
        metadata.mergeTree("javax_imageio_1.0", root);
    }

    writer.write(null, new IIOImage(img, null, metadata), null);
    return output.toByteArray();
}

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  ww  w.  ja va2s .  c om
    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:ch5ImageWriter.java

/**
 * write out the output image specified by index imageIndex using the
 * parameters specified by the ImageWriteParam object param
 *//*  w  ww  .j a va2s.  c  om*/
public void write(IIOMetadata metadata, IIOImage iioimage, ImageWriteParam param) {
    Node root = null;
    Node dimensionsElementNode = null;

    if (iioimage.getRenderedImage() != null)
        raster = iioimage.getRenderedImage().getData();
    else
        raster = iioimage.getRaster();

    /*
     * since this format allows you to write multiple images, the
     * streamMetadataWritten variable makes sure the stream metadata is
     * written only once
     */
    if (streamMetadataWritten == false) {
        if (metadata == null)
            metadata = getDefaultStreamMetadata(param);
        root = metadata.getAsTree("ch5.imageio.ch5stream_1.00");
        dimensionsElementNode = root.getFirstChild();
        Node numberImagesAttributeNode = dimensionsElementNode.getAttributes().getNamedItem("numberImages");
        String numberImages = numberImagesAttributeNode.getNodeValue();
        try {
            ios.writeBytes("5\n");
            ios.writeBytes(numberImages);
            ios.flush();
        } catch (IOException ioe) {
            System.err.println("IOException " + ioe.getMessage());
        }
        streamMetadataWritten = true;
    }

    String widthString;
    String heightString;
    IIOMetadata imageMetadata = (ch5ImageMetadata) iioimage.getMetadata();
    /*
     * don't really need image metadata object here since raster knows
     * necessary information
     */
    if (imageMetadata == null)
        imageMetadata = getDefaultImageMetadata(null, param);

    root = imageMetadata.getAsTree("ch5.imageio.ch5image_1.00");
    dimensionsElementNode = root.getFirstChild();

    Node widthAttributeNode = dimensionsElementNode.getAttributes().getNamedItem("imageWidth");
    widthString = widthAttributeNode.getNodeValue();

    Node heightAttributeNode = dimensionsElementNode.getAttributes().getNamedItem("imageHeight");
    heightString = heightAttributeNode.getNodeValue();

    int sourceWidth = Integer.parseInt(widthString);
    int sourceHeight = Integer.parseInt(heightString);
    int destinationWidth = -1;
    int destinationHeight = -1;
    int sourceRegionWidth = -1;
    int sourceRegionHeight = -1;
    int sourceRegionXOffset = -1;
    int sourceRegionYOffset = -1;
    int xSubsamplingFactor = -1;
    int ySubsamplingFactor = -1;

    if (param == null)
        param = getDefaultWriteParam();

    /*
     * get Rectangle object which will be used to clip the source image's
     * dimensions.
     */
    Rectangle sourceRegion = param.getSourceRegion();
    if (sourceRegion != null) {
        sourceRegionWidth = (int) sourceRegion.getWidth();
        sourceRegionHeight = (int) sourceRegion.getHeight();
        sourceRegionXOffset = (int) sourceRegion.getX();
        sourceRegionYOffset = (int) sourceRegion.getY();

        /*
         * correct for overextended source regions
         */
        if (sourceRegionXOffset + sourceRegionWidth > sourceWidth)
            destinationWidth = sourceWidth - sourceRegionXOffset;
        else
            destinationWidth = sourceRegionWidth;

        if (sourceRegionYOffset + sourceRegionHeight > sourceHeight)
            destinationHeight = sourceHeight - sourceRegionYOffset;
        else
            destinationHeight = sourceRegionHeight;
    } else {
        destinationWidth = sourceWidth;
        destinationHeight = sourceHeight;
        sourceRegionXOffset = sourceRegionYOffset = 0;
    }
    /*
     * get subsampling factors
     */
    xSubsamplingFactor = param.getSourceXSubsampling();
    ySubsamplingFactor = param.getSourceYSubsampling();

    destinationWidth = (destinationWidth - 1) / xSubsamplingFactor + 1;
    destinationHeight = (destinationHeight - 1) / ySubsamplingFactor + 1;

    byte[] sourceBuffer;
    byte[] destinationBuffer = new byte[destinationWidth];

    try {
        ios.writeBytes(new String("\n"));
        ios.writeBytes(new String(destinationWidth + "\n"));
        ios.writeBytes(new String(destinationHeight + "\n"));

        int jj;
        int index;
        for (int j = 0; j < sourceWidth; j++) {
            sourceBuffer = (byte[]) raster.getDataElements(0, j, sourceWidth, 1, null);
            jj = j - sourceRegionYOffset;
            if (jj % ySubsamplingFactor == 0) {
                jj /= ySubsamplingFactor;
                if ((jj >= 0) && (jj < destinationHeight)) {
                    for (int i = 0; i < destinationWidth; i++) {
                        index = sourceRegionXOffset + i * xSubsamplingFactor;
                        destinationBuffer[i] = sourceBuffer[index];
                    }
                    ios.write(destinationBuffer, 0, destinationWidth);
                    ios.flush();
                }
            }
        }
    } catch (IOException e) {
        System.err.println("IOException: " + e.getMessage());
    }
}

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  a2  s . c  o 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);
    }
}

From source file:lucee.runtime.img.Image.java

public IIOMetadata getMetaData(Struct parent) {
    InputStream is = null;/* www . j  a  va  2 s.  co  m*/
    javax.imageio.stream.ImageInputStreamImpl iis = null;
    try {

        if (source instanceof File) {
            iis = new FileImageInputStream((File) source);
        } else if (source == null)
            iis = new MemoryCacheImageInputStream(new ByteArrayInputStream(getImageBytes(format, true)));
        else
            iis = new MemoryCacheImageInputStream(is = source.getInputStream());

        Iterator<ImageReader> readers = ImageIO.getImageReaders(iis);
        if (readers.hasNext()) {
            // pick the first available ImageReader
            ImageReader reader = readers.next();
            IIOMetadata meta = null;
            synchronized (sync) {
                // attach source to the reader
                reader.setInput(iis, true);

                // read metadata of first image
                meta = reader.getImageMetadata(0);
                meta.setFromTree(FORMAT, meta.getAsTree(FORMAT));
                reader.reset();
            }
            // generating dump
            if (parent != null) {
                String[] formatNames = meta.getMetadataFormatNames();
                for (int i = 0; i < formatNames.length; i++) {
                    Node root = meta.getAsTree(formatNames[i]);
                    //print.out(XMLCaster.toString(root));
                    addMetaddata(parent, "metadata", root);
                }
            }
            return meta;
        }
    } catch (Throwable t) {
    } finally {
        ImageUtil.closeEL(iis);
        IOUtil.closeEL(is);
    }
    return null;
}

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

/** {@inheritDoc} */
public Image loadImage(ImageInfo info, Map hints, ImageSessionContext session)
        throws ImageException, IOException {
    RenderedImage imageData = null;
    IIOException firstException = null;

    IIOMetadata iiometa = (IIOMetadata) info.getCustomObjects().get(ImageIOUtil.IMAGEIO_METADATA);
    boolean ignoreMetadata = (iiometa != null);
    boolean providerIgnoresICC = false;

    Source src = session.needSource(info.getOriginalURI());
    ImageInputStream imgStream = ImageUtil.needImageInputStream(src);
    try {//  w w w. j  a  v a 2 s.c  om
        Iterator iter = ImageIO.getImageReaders(imgStream);
        while (iter.hasNext()) {
            ImageReader reader = (ImageReader) iter.next();
            try {
                imgStream.mark();
                ImageReadParam param = reader.getDefaultReadParam();
                reader.setInput(imgStream, false, ignoreMetadata);
                final int pageIndex = ImageUtil.needPageIndexFromURI(info.getOriginalURI());
                try {
                    if (ImageFlavor.BUFFERED_IMAGE.equals(this.targetFlavor)) {
                        imageData = reader.read(pageIndex, param);
                    } else {
                        imageData = reader.read(pageIndex, param);
                        //imageData = reader.readAsRenderedImage(pageIndex, param);
                        //TODO Reenable the above when proper listeners are implemented
                        //to react to late pixel population (so the stream can be closed
                        //properly).
                    }
                    if (iiometa == null) {
                        iiometa = reader.getImageMetadata(pageIndex);
                    }
                    providerIgnoresICC = checkProviderIgnoresICC(reader.getOriginatingProvider());
                    break; //Quit early, we have the image
                } catch (IndexOutOfBoundsException indexe) {
                    throw new ImageException("Page does not exist. Invalid image index: " + pageIndex);
                } catch (IllegalArgumentException iae) {
                    //Some codecs like com.sun.imageio.plugins.wbmp.WBMPImageReader throw
                    //IllegalArgumentExceptions when they have trouble parsing the image.
                    throw new ImageException("Error loading image using ImageIO codec", iae);
                } catch (IIOException iioe) {
                    if (firstException == null) {
                        firstException = iioe;
                    } else {
                        log.debug("non-first error loading image: " + iioe.getMessage());
                    }
                }
                try {
                    //Try fallback for CMYK images
                    BufferedImage bi = getFallbackBufferedImage(reader, pageIndex, param);
                    imageData = bi;
                    firstException = null; //Clear exception after successful fallback attempt
                    break;
                } catch (IIOException iioe) {
                    //ignore
                }
                imgStream.reset();
            } finally {
                reader.dispose();
            }
        }
    } finally {
        ImageUtil.closeQuietly(src);
        //TODO Some codecs may do late reading.
    }
    if (firstException != null) {
        throw new ImageException("Error while loading image: " + firstException.getMessage(), firstException);
    }
    if (imageData == null) {
        throw new ImageException("No ImageIO ImageReader found .");
    }

    ColorModel cm = imageData.getColorModel();

    Color transparentColor = null;
    if (cm instanceof IndexColorModel) {
        //transparent color will be extracted later from the image
    } else {
        if (providerIgnoresICC && cm instanceof ComponentColorModel) {
            // Apply ICC Profile to Image by creating a new image with a new
            // color model.
            ICC_Profile iccProf = tryToExctractICCProfile(iiometa);
            if (iccProf != null) {
                ColorModel cm2 = new ComponentColorModel(new ICC_ColorSpace(iccProf), cm.hasAlpha(),
                        cm.isAlphaPremultiplied(), cm.getTransparency(), cm.getTransferType());
                WritableRaster wr = Raster.createWritableRaster(imageData.getSampleModel(), null);
                imageData.copyData(wr);
                BufferedImage bi = new BufferedImage(cm2, wr, cm2.isAlphaPremultiplied(), null);
                imageData = bi;
                cm = cm2;
            }
        }
        // ImageIOUtil.dumpMetadataToSystemOut(iiometa);
        // Retrieve the transparent color from the metadata
        if (iiometa != null && iiometa.isStandardMetadataFormatSupported()) {
            Element metanode = (Element) iiometa.getAsTree(IIOMetadataFormatImpl.standardMetadataFormatName);
            Element dim = ImageIOUtil.getChild(metanode, "Transparency");
            if (dim != null) {
                Element child;
                child = ImageIOUtil.getChild(dim, "TransparentColor");
                if (child != null) {
                    String value = child.getAttribute("value");
                    if (value == null || value.length() == 0) {
                        //ignore
                    } else if (cm.getNumColorComponents() == 1) {
                        int gray = Integer.parseInt(value);
                        transparentColor = new Color(gray, gray, gray);
                    } else {
                        StringTokenizer st = new StringTokenizer(value);
                        transparentColor = new Color(Integer.parseInt(st.nextToken()),
                                Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()));
                    }
                }
            }
        }
    }

    if (ImageFlavor.BUFFERED_IMAGE.equals(this.targetFlavor)) {
        return new ImageBuffered(info, (BufferedImage) imageData, transparentColor);
    } else {
        return new ImageRendered(info, imageData, transparentColor);
    }
}