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:eu.europa.esig.dss.pades.signature.visible.ImageFactory.java

private static void initDpi(IIOMetadata metadata, int dpi) throws IIOInvalidTreeException {
    Element tree = (Element) metadata.getAsTree("javax_imageio_jpeg_image_1.0");
    Element jfif = (Element) tree.getElementsByTagName("app0JFIF").item(0);
    jfif.setAttribute("Xdensity", Integer.toString(dpi));
    jfif.setAttribute("Ydensity", Integer.toString(dpi));
    jfif.setAttribute("resUnits", "1"); // density is dots per inch
    metadata.setFromTree("javax_imageio_jpeg_image_1.0", tree);
}

From source file:de.mpg.imeji.presentation.metadata.extractors.BasicExtractor.java

public static List<String> extractTechMd(Item item) throws Exception {
    List<String> techMd = new ArrayList<String>();
    URI uri = item.getFullImageUrl();
    String imageUrl = uri.toURL().toString();
    GetMethod method = new GetMethod(imageUrl);
    method.setFollowRedirects(false);//from w  w  w . ja v  a2  s  . c o m
    String userHandle = null;
    userHandle = LoginHelper.login(PropertyReader.getProperty("imeji.escidoc.user"),
            PropertyReader.getProperty("imeji.escidoc.password"));
    method.addRequestHeader("Cookie", "escidocCookie=" + userHandle);
    HttpClient client = new HttpClient();
    client.executeMethod(method);
    InputStream input = method.getResponseBodyAsStream();
    ImageInputStream iis = ImageIO.createImageInputStream(input);
    Iterator<ImageReader> readers = ImageIO.getImageReaders(iis);
    if (readers.hasNext()) {
        // pick the first available ImageReader
        ImageReader reader = readers.next();
        // attach source to the reader
        reader.setInput(iis, true);
        // read metadata of first image
        IIOMetadata metadata = reader.getImageMetadata(0);
        String[] names = metadata.getMetadataFormatNames();
        int length = names.length;
        for (int i = 0; i < length; i++) {
            displayMetadata(techMd, metadata.getAsTree(names[i]));
        }
    }
    return techMd;
}

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

static void debugLogMetadata(IIOMetadata metadata, String format) {
    if (!LOG.isDebugEnabled()) {
        return;/*from w w  w  .ja  v  a2s. c om*/
    }

    // see http://docs.oracle.com/javase/7/docs/api/javax/imageio/
    //     metadata/doc-files/standard_metadata.html
    IIOMetadataNode root = (IIOMetadataNode) metadata.getAsTree(format);
    try {
        StringWriter xmlStringWriter = new StringWriter();
        StreamResult streamResult = new StreamResult(xmlStringWriter);
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        // see http://stackoverflow.com/a/1264872/535646
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        DOMSource domSource = new DOMSource(root);
        transformer.transform(domSource, streamResult);
        LOG.debug("\n" + xmlStringWriter);
    } catch (IllegalArgumentException ex) {
        LOG.error(ex, ex);
    } catch (TransformerException ex) {
        LOG.error(ex, ex);
    }
}

From source file:org.apache.pdfbox.util.ImageIOUtil.java

private static void setDPI(IIOMetadata metadata, int dpi, String formatName) {
    IIOMetadataNode root = (IIOMetadataNode) metadata.getAsTree(STANDARD_METADATA_FORMAT);

    IIOMetadataNode dimension = getOrCreateChildNode(root, "Dimension");

    // PNG writer doesn't conform to the spec which is
    // "The width of a pixel, in millimeters"
    // but instead counts the pixels per millimeter
    float res = "PNG".equals(formatName.toUpperCase()) ? dpi / 25.4f : 25.4f / dpi;

    IIOMetadataNode child;/*w  w  w.  j  a va 2s  . co m*/

    child = getOrCreateChildNode(dimension, "HorizontalPixelSize");
    child.setAttribute("value", Double.toString(res));

    child = getOrCreateChildNode(dimension, "VerticalPixelSize");
    child.setAttribute("value", Double.toString(res));

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

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

private static void setDPI(IIOMetadata metadata, int dpi, String formatName) throws IIOInvalidTreeException {
    IIOMetadataNode root = (IIOMetadataNode) metadata.getAsTree(MetaUtil.STANDARD_METADATA_FORMAT);

    IIOMetadataNode dimension = getOrCreateChildNode(root, "Dimension");

    // PNG writer doesn't conform to the spec which is
    // "The width of a pixel, in millimeters"
    // but instead counts the pixels per millimeter
    float res = "PNG".equals(formatName.toUpperCase()) ? dpi / 25.4f : 25.4f / dpi;

    IIOMetadataNode child;//from www  . j  av a 2  s.  c  o  m

    child = getOrCreateChildNode(dimension, "HorizontalPixelSize");
    child.setAttribute("value", Double.toString(res));

    child = getOrCreateChildNode(dimension, "VerticalPixelSize");
    child.setAttribute("value", Double.toString(res));

    metadata.mergeTree(MetaUtil.STANDARD_METADATA_FORMAT, root);
}

From source file:org.sejda.sambox.pdmodel.graphics.image.JPEGFactory.java

private static void encodeImageToJPEGStream(BufferedImage image, float quality, int dpi, OutputStream out)
        throws IOException {
    // encode to JPEG
    ImageOutputStream ios = null;
    ImageWriter imageWriter = null;
    try {//from  w w  w. ja va 2  s. c  o m
        // find JAI writer
        imageWriter = ImageIO.getImageWritersBySuffix("jpeg").next();
        ios = ImageIO.createImageOutputStream(out);
        imageWriter.setOutput(ios);

        // add compression
        JPEGImageWriteParam jpegParam = (JPEGImageWriteParam) imageWriter.getDefaultWriteParam();
        jpegParam.setCompressionMode(JPEGImageWriteParam.MODE_EXPLICIT);
        jpegParam.setCompressionQuality(quality);

        // add metadata
        ImageTypeSpecifier imageTypeSpecifier = new ImageTypeSpecifier(image);
        IIOMetadata data = imageWriter.getDefaultImageMetadata(imageTypeSpecifier, jpegParam);
        Element tree = (Element) data.getAsTree("javax_imageio_jpeg_image_1.0");
        Element jfif = (Element) tree.getElementsByTagName("app0JFIF").item(0);
        jfif.setAttribute("Xdensity", Integer.toString(dpi));
        jfif.setAttribute("Ydensity", Integer.toString(dpi));
        jfif.setAttribute("resUnits", "1"); // 1 = dots/inch

        // write
        imageWriter.write(data, new IIOImage(image, null, null), jpegParam);
    } finally {
        // clean up
        IOUtils.closeQuietly(out);
        if (ios != null) {
            ios.close();
        }
        if (imageWriter != null) {
            imageWriter.dispose();
        }
    }
}

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

public static SketchyImage load(File file) throws Exception {
    SketchyImage sketchyImage = null;//from   w  w w.ja va 2  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:org.apache.tika.parser.image.ImageParser.java

private static void loadMetadata(IIOMetadata imageMetadata, Metadata metadata) {
    if (imageMetadata == null) {
        return;//from  w  w  w.  j a v a2 s  .  com
    }
    String[] names = imageMetadata.getMetadataFormatNames();
    if (names == null) {
        return;
    }
    for (String name : names) {
        loadNode(metadata, imageMetadata.getAsTree(name), "", false);
    }
}

From source file:net.rptools.tokentool.util.ImageUtil.java

private static ImageView getImage(ImageView thumbView, final Path filePath, final boolean overlayWanted,
        final int THUMB_SIZE) throws IOException {
    Image thumb = null;//from  w  ww  .  ja  v a2s.c  om
    String fileURL = filePath.toUri().toURL().toString();

    if (ImageUtil.SUPPORTED_IMAGE_FILE_FILTER.accept(null, fileURL)) {
        if (THUMB_SIZE <= 0)
            thumb = processMagenta(new Image(fileURL), COLOR_THRESHOLD, overlayWanted);
        else
            thumb = processMagenta(new Image(fileURL, THUMB_SIZE, THUMB_SIZE, true, true), COLOR_THRESHOLD,
                    overlayWanted);
    } else if (ImageUtil.PSD_FILE_FILTER.accept(null, fileURL)) {
        ImageInputStream is = null;
        PSDImageReader reader = null;
        int imageIndex = 1;

        // Mask layer should always be layer 1 and overlay image on layer 2. Note, layer 0 will be a combined layer composite
        if (overlayWanted)
            imageIndex = 2;

        File file = filePath.toFile();

        try {
            is = ImageIO.createImageInputStream(file);
            if (is == null || is.length() == 0) {
                log.info("Image from file " + file.getAbsolutePath() + " is null");
            }

            Iterator<ImageReader> iterator = ImageIO.getImageReaders(is);
            if (iterator == null || !iterator.hasNext()) {
                throw new IOException("Image file format not supported by ImageIO: " + filePath);
            }

            reader = (PSDImageReader) iterator.next();
            reader.setInput(is);
            BufferedImage thumbBI;
            thumbBI = reader.read(imageIndex);

            if (thumbBI != null) {
                int layerIndex = 0;
                if (overlayWanted)
                    layerIndex = 1;

                IIOMetadata metadata = reader.getImageMetadata(0);
                IIOMetadataNode root = (IIOMetadataNode) metadata
                        .getAsTree(PSDMetadata.NATIVE_METADATA_FORMAT_NAME);
                NodeList layerInfos = root.getElementsByTagName("LayerInfo");

                // Layer index corresponds to imageIndex - 1 in the reader
                IIOMetadataNode layerInfo = (IIOMetadataNode) layerInfos.item(layerIndex);

                // Get the width & height of the Mask layer so we can create the overlay the same size
                int width = reader.getWidth(0);
                int height = reader.getHeight(0);

                // Get layer offsets, PhotoShop PSD layers can have different widths/heights and all images start at 0,0 with a layer offset applied
                int x = Math.max(Integer.parseInt(layerInfo.getAttribute("left")), 0);
                int y = Math.max(Integer.parseInt(layerInfo.getAttribute("top")), 0);

                // Lets pad the overlay with transparency to make it the same size as the PSD canvas size
                thumb = resizeCanvas(SwingFXUtils.toFXImage(thumbBI, null), width, height, x, y);

                // Finally set ImageView to thumbnail size
                if (THUMB_SIZE > 0) {
                    thumbView.setFitWidth(THUMB_SIZE);
                    thumbView.setPreserveRatio(true);
                }
            }
        } catch (Exception e) {
            log.error("Processing: " + file.getAbsolutePath(), e);
        } finally {
            // Dispose reader in finally block to avoid memory leaks
            reader.dispose();
            is.close();
        }
    }

    thumbView.setImage(thumb);

    return thumbView;
}

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() + "!");
    }// ww  w .j a  va 2 s .  co  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);
    }
}