IIOMetadata metadata

This post asks about image metadata.
IIOMetadata meta = reader.getImageMetadata(0);
when meta.getAsTree( meta.getNativeMetadataFormatName() ) is used to retrieve image metadata one gets Nodes like this:
<javax_imageio_jpeg_image_1.0>
<JPEGvariety>
<app0JFIF/>
</JPEGvariety>
<markerSequence>
<dqt>
<dqtable/>
Using meta.getMetadataFormatNames() and meta.getExtraMetadataFormatNames() a typical JPEG lists the following formats:
javax_imageio_jpeg_image_1.0
javax_imageio_1.0
- the former is the format returned by .getNativeMetadataFormatName().
I have been unsuccessful in retreiving any metadata from any listed format in this way for images having known metadata stored in them by applications like: Photoshop, PaintshopPro or Windows Explorer's 'summary' tab. Who knows what the magic String is that reveals all the yummy metadata in my images ? Do I need to write my own IIOMetadata that understands where to look in the PNG chunks, JPEG markers and TIFF tags and builds a big Node from the name=value pairs therein ? What about EXIF metadata ? Can I get that out using IIOMetadata or should I write that myself ?

I'm having problems with trying to modify the default metadata for an image, and store that modified metadata when I save the image as a JPEG. I'm trying to create a 150 DPI JPEG, and so I am trying to change the resUnits, Xdensity, and Ydensity attribute values.
Well I can change the values in the Node objects, but when I write out the JPEG the metadata seems to be ignored.
Also, if I try to merge my metadata changes I get an exception:
java.lang.NullPointerException
     at com.sun.imageio.plugins.jpeg.MarkerSegment.getAttributeValue(MarkerSegment.java:131)
     at com.sun.imageio.plugins.jpeg.JPEGMetadata.mergeDHTNode(JPEGMetadata.java:1254)
     at com.sun.imageio.plugins.jpeg.JPEGMetadata.mergeSequenceSubtree(JPEGMetadata.java:1127)
     at com.sun.imageio.plugins.jpeg.JPEGMetadata.mergeNativeTree(JPEGMetadata.java:1092)
     at com.sun.imageio.plugins.jpeg.JPEGMetadata.mergeTree(JPEGMetadata.java:1064)
     at com.eentertainment.graphicTools.JPEGMaker.main(JPEGMaker.java:307)
Exception in thread "main" Process terminated with exit code 1
After two days of banging my head against the monitor, my head hurts =`)

Similar Messages

  • ImageIO, TIFF, and metadata problems

    I'm trying to set some metadata parameters for output of a TIFF image. The problem I had was, the API returns a W3C DOM Node, and since the DOM API is so disgusting, I didn't want to use it directly.
    And naturally, since XPath is supposed to work over a DOM, I thought I could use it as a shortcut.
    Sample program:
    import java.awt.image.BufferedImage;
    import java.awt.image.RenderedImage;
    import javax.imageio.metadata.IIOMetadata;
    import javax.imageio.ImageIO;
    import javax.imageio.ImageTypeSpecifier;
    import javax.imageio.ImageWriteParam;
    import javax.imageio.ImageWriter;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    import javax.xml.xpath.XPath;
    import javax.xml.xpath.XPathConstants;
    import javax.xml.xpath.XPathFactory;
    import org.w3c.dom.Node;
    public class TiffMetadataBug {
        public static void main(String[] args) throws Exception {
            // Test image
            RenderedImage image = new BufferedImage(8, 8, BufferedImage.TYPE_INT_ARGB);
            // Get the default metadata for this kind of image
            ImageWriter imageWriter = ImageIO.getImageWritersByFormatName("TIFF").next();
            ImageWriteParam writeParam = imageWriter.getDefaultWriteParam();
            IIOMetadata metadata = imageWriter.getDefaultImageMetadata(new ImageTypeSpecifier(image), writeParam);
            // The root metadata node is...
            Node metadataRoot = metadata.getAsTree(metadata.getNativeMetadataFormatName());
            // Output the metadata DOM as XML.
            Transformer identity = TransformerFactory.newInstance().newTransformer();
            System.out.print("XML:");
            identity.transform(new DOMSource(metadataRoot), new StreamResult(System.out));
            System.out.println();
            // Try to match a path into the DOM.
            XPath xPath = XPathFactory.newInstance().newXPath();
            Object result = xPath.evaluate("//TIFFField[@number='282']/TIFFRationals/TIFFRational", metadataRoot, XPathConstants.NODE);
            System.out.println("Result of XPath evaluation: " + result);
    }The first bit of the output was done to see what XPath to use. It contains XML like this:
        <TIFFField number="282" name="XResolution">
            <TIFFRationals>
                <TIFFRational value="1/1"/>
            </TIFFRationals>
        </TIFFField>So my XPath:
    //TIFFField[@number='282']/TIFFRationals/TIFFRationalshould work fine.
    I wonder if this is a bug in the ImageIO metadata code, or if I'm actually doing something wrong here.

    Hi!
    I try to get tiff tags together with their data out of a TIFF-file with the use of DOM. I get problems reading the metadata. How can I read metadata so I can output it like above?
    thanks in advanced.
    Errors I get:
    Exception in thread "main" javax.imageio.IIOException: I/O error reading image metadata!
    at com.sun.media.imageioimpl.plugins.tiff.TIFFImageReader.readMetadata(Unknown Source)
    at com.sun.media.imageioimpl.plugins.tiff.TIFFImageReader.seekToImage(Unknown Source)
    at com.sun.media.imageioimpl.plugins.tiff.TIFFImageReader.getImageMetadata(Unknown Source)
    at tiffmetadatabug.Main.main(Main.java:96)
    Caused by: java.io.EOFException
    at javax.imageio.stream.ImageInputStreamImpl.readShort(ImageInputStreamImpl.java:211)
    at javax.imageio.stream.ImageInputStreamImpl.readUnsignedShort(ImageInputStreamImpl.java:222)
    at com.sun.media.imageioimpl.plugins.tiff.TIFFIFD.initialize(Unknown Source)
    at com.sun.media.imageioimpl.plugins.tiff.TIFFIFD.initialize(Unknown Source)
    at com.sun.media.imageioimpl.plugins.tiff.TIFFImageMetadata.initializeFromStream(Unknown Source)
    ... 4 more
    Java Result: 1

  • How to read the EXIF metadata from a .jpg file

    hi,every one
    Photos which are captured by a digital camera, have some parameters, such as the exposure time,ISO speed rating,camera model,focal length etc.
    How to read this parameters???

    Is it listed in the IIOMetadata?
    import java.awt.*;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import javax.imageio.*;
    import javax.imageio.metadata.*;
    import org.w3c.dom.*;
    public class IIOMetaDataExample {
        public static void main(String[] args) throws IOException {
            URL url = new URL("http://today.java.net/jag/bio/JagHeadshot-small.jpg");
            Iterator readers = ImageIO.getImageReadersBySuffix("jpeg");
            ImageReader reader = (ImageReader) readers.next();
            reader.setInput(ImageIO.createImageInputStream(url.openStream()));
            IIOMetadata metadata = reader.getImageMetadata(0);
            displayMetadata(metadata);
        public static void displayMetadata(IIOMetadata metadata) {
            String[] names = metadata.getMetadataFormatNames();
            for(int i=0; i<names.length; ++i) {
                System.out.println();
                System.out.println("METADATA FOR FORMAT: " + names);
    displayTree(metadata.getAsTree(names[i]), 0);
    public static void displayTree(Node node, int indent) {
    indent(indent);
    String name = node.getNodeName();
    System.out.print("<" + name);
    if (node.hasAttributes()) {
    NamedNodeMap attrs = node.getAttributes();
    for(int i=0, ub=attrs.getLength(); i<ub; ++i) {
    Node attr = attrs.item(i);
    System.out.print(" " + attr.getNodeName() + "=" + attr.getNodeValue());
    if (node.hasChildNodes()) {
    System.out.println(">");
    NodeList children = node.getChildNodes();
    for(int i=0,ub=children.getLength(); i<ub; ++i)
    displayTree(children.item(i), indent+4);
    indent(indent);
    System.out.println("</" + name +">");
    } else
    System.out.println("/>");
    static void indent(int indent) {
    for(int i=0; i<indent; ++i)
    System.out.print(' ');

  • Create animated GIF using imageio

    How do you create an animated GIF using the J2SE's javax.imageio classes?
    I have been browsing these 3 threads (one of which I participated in) to try and develop an SSCCE of creating an animated GIF.
    [Writing out animated gifs with ImageIO?|http://forums.sun.com/thread.jspa?threadID=5204877]
    [Wirting image metadata to control animated gif delays |http://forums.java.net/jive/thread.jspa?messageID=214284&]
    [Help with GIF writer in imageio|http://www.javakb.com/Uwe/Forum.aspx/java-programmer/32892/Help-with-GIF-writer-in-imageio]
    (pity I did not prompt the OP on that last one, to supply an SSCCE.)
    Unfortunately, my efforts so far have been dismal. Either, without the IIOMetadata object, the GIF has frames with no delay, and it cycles just once, or with the IIOMetadata object I get an error.
    IIOInvalidTreeException: Unknown child of root node!Can anyone point me in the right direction?
    import java.awt.*;
    import java.awt.image.*;
    import javax.swing.*;
    import java.io.*;
    import java.net.URL;
    import java.util.Iterator;
    import javax.imageio.*;
    import javax.imageio.metadata.*;
    import javax.imageio.stream.*;
    import org.w3c.dom.Node;
    class WriteAnimatedGif {
      /** Adapted from code via Brian Burkhalter on
      http://forums.java.net/jive/thread.jspa?messageID=214284& */
      public static Node getRootNode(String delayTime) {
        IIOMetadataNode root =
          new IIOMetadataNode("javax_imageio_gif_stream_1.0");
        IIOMetadataNode gce =
          new IIOMetadataNode("GraphicControlExtension");
        gce.setAttribute("disposalMethod", "none");
        gce.setAttribute("userInputFlag", "FALSE");
        gce.setAttribute("transparentColorFlag", "FALSE");
        gce.setAttribute("delayTime", delayTime);
        gce.setAttribute("transparentColorIndex", "255");
        root.appendChild(gce);
        IIOMetadataNode aes =
          new IIOMetadataNode("ApplicationExtensions");
        IIOMetadataNode ae =
          new IIOMetadataNode("ApplicationExtension");
        ae.setAttribute("applicationID", "NETSCAPE");
        ae.setAttribute("authenticationCode", "2.0");
        byte[] uo = new byte[] {
          (byte)0x21, (byte)0xff, (byte)0x0b,
          (byte)'N', (byte)'E', (byte)'T', (byte)'S',
          (byte)'C', (byte)'A', (byte)'P', (byte)'E',
          (byte)'2', (byte)'.', (byte)'0',
          (byte)0x03, (byte)0x01, (byte)0x00, (byte)0x00,
          (byte)0x00
        ae.setUserObject(uo);
        aes.appendChild(ae);
        root.appendChild(aes);
        return root;
      /** Adapted from code via GeogffTitmus on
      http://forums.sun.com/thread.jspa?messageID=9988198 */
      public static File saveAnimate(
        BufferedImage[] frames,
        String name,
        String delayTime) throws Exception {
        File file = null;
        file = new File(name+".gif");
        Node root = getRootNode(delayTime);
        ImageWriter iw = ImageIO.getImageWritersByFormatName("gif").next();
        ImageOutputStream ios = ImageIO.createImageOutputStream(file);
        iw.setOutput(ios);
        //IIOImage ii = new IIOImage(frames[0], null, null);
        //IIOMetadata im = iw.getDefaultStreamMetadata(null);
        //IIOMetadata im = new AnimatedIIOMetadata();
        //im.setFromTree("gif", root);
        iw.prepareWriteSequence(null);
        for (int i = 0; i < frames.length; i++) {
          BufferedImage src = frames;
    ImageWriteParam iwp = iw.getDefaultWriteParam();
    IIOMetadata metadata = iw.getDefaultStreamMetadata(iwp);
    System.out.println( "IIOMetadata: " + metadata );
    //metadata.mergeTree(metadata.getNativeMetadataFormatName(), root);
    metadata.setFromTree(metadata.getNativeMetadataFormatName(), root);
    //Node root = metadata.getAsTree("javax_imageio_gif_image_1.0");
    IIOImage ii = new IIOImage(src, null, metadata);
    iw.writeToSequence( ii, (ImageWriteParam)null);
    iw.endWriteSequence();
    ios.close();
    return file;
    public static void main(String[] args) throws Exception {
    // uncomment the other two if you like, but we can
    // see it work or fail with just the first and last.
    String[] names = {
    "bronze",
    //"silver",
    //"gold",
    "platinum"
    String pre = "http://forums.sun.com/im/";
    String suff = "-star.gif";
    BufferedImage[] frames = new BufferedImage[names.length];
    for (int ii=0; ii<names.length; ii++) {
    URL url = new URL(pre + names[ii] + suff);
    System.out.println(url);
    frames[ii] = ImageIO.read(url);
    File f = saveAnimate(frames, "animatedstars", "500");
    JOptionPane.showMessageDialog( null, new ImageIcon(f.toURI().toURL()) );
    Desktop.getDesktop().open(f);
    ImageInputStream iis = ImageIO.createImageInputStream(f);
    //System.out.println("ImageReader: " + ir1);
    //System.out.println("IIOMetadata: " + ir1.getStreamMetadata());
    Iterator itReaders = ImageIO.getImageReaders(iis);
    while (itReaders.hasNext() ) {
    ImageReader ir = (ImageReader)itReaders.next();
    System.out.println("ImageReader: " + ir);
    System.out.println("IIOMetadata: " + ir.getStreamMetadata());

    According to imagio's [gif metadata specification|http://java.sun.com/javase/6/docs/api/javax/imageio/metadata/doc-files/gif_metadata.html], the metadata you are specifying is image-specific metadata. The stream metadata is global metadata applicable to all the images.
    So change this,
    IIOMetadataNode root =
        new IIOMetadataNode("javax_imageio_gif_stream_1.0");to this,
    IIOMetadataNode root =
        new IIOMetadataNode("javax_imageio_gif_image_1.0");and this,
    IIOMetadata metadata = iw.getDefaultStreamMetadata(iwp);
    System.out.println( "IIOMetadata: " + metadata );
    //metadata.mergeTree(metadata.getNativeMetadataFormatName(), root);
    metadata.setFromTree(metadata.getNativeMetadataFormatName(), root);
    //Node root = metadata.getAsTree("javax_imageio_gif_image_1.0");to this,
    IIOMetadata metadata = iw.getDefaultImageMetadata(
            new ImageTypeSpecifier(src),null);
    System.out.println("IIOMetadata: " + metadata);
    metadata.mergeTree(metadata.getNativeMetadataFormatName(), root);Here is your program again, but with the above changes.
    import java.awt.*;
    import java.awt.image.*;
    import javax.swing.*;
    import java.io.*;
    import java.net.URL;
    import java.util.Iterator;
    import javax.imageio.*;
    import javax.imageio.metadata.*;
    import javax.imageio.stream.*;
    import org.w3c.dom.Node;
    class WriteAnimatedGif {
        /** Adapted from code via Brian Burkhalter on
        http://forums.java.net/jive/thread.jspa?messageID=214284& */
        public static Node getRootNode(String delayTime) {
            IIOMetadataNode root =
                    new IIOMetadataNode("javax_imageio_gif_image_1.0");
            IIOMetadataNode gce =
                    new IIOMetadataNode("GraphicControlExtension");
            gce.setAttribute("disposalMethod", "none");
            gce.setAttribute("userInputFlag", "FALSE");
            gce.setAttribute("transparentColorFlag", "FALSE");
            gce.setAttribute("delayTime", delayTime);
            gce.setAttribute("transparentColorIndex", "255");
            root.appendChild(gce);
            IIOMetadataNode aes =
                    new IIOMetadataNode("ApplicationExtensions");
            IIOMetadataNode ae =
                    new IIOMetadataNode("ApplicationExtension");
            ae.setAttribute("applicationID", "NETSCAPE");
            ae.setAttribute("authenticationCode", "2.0");
            byte[] uo = new byte[]{
                (byte) 0x21, (byte) 0xff, (byte) 0x0b,
                (byte) 'N', (byte) 'E', (byte) 'T', (byte) 'S',
                (byte) 'C', (byte) 'A', (byte) 'P', (byte) 'E',
                (byte) '2', (byte) '.', (byte) '0',
                (byte) 0x03, (byte) 0x01, (byte) 0x00, (byte) 0x00,
                (byte) 0x00
            ae.setUserObject(uo);
            aes.appendChild(ae);
            root.appendChild(aes);
            return root;
        /** Adapted from code via GeogffTitmus on
        http://forums.sun.com/thread.jspa?messageID=9988198 */
        public static File saveAnimate(
                BufferedImage[] frames,
                String name,
                String delayTime) throws Exception {
            File file = null;
            file = new File(name + ".gif");
            Node root = getRootNode(delayTime);
            ImageWriter iw = ImageIO.getImageWritersByFormatName("gif").next();
            ImageOutputStream ios = ImageIO.createImageOutputStream(file);
            iw.setOutput(ios);
            //IIOImage ii = new IIOImage(frames[0], null, null);
            //IIOMetadata im = iw.getDefaultStreamMetadata(null);
            //IIOMetadata im = new AnimatedIIOMetadata();
            //im.setFromTree("gif", root);
            iw.prepareWriteSequence(null);
            for (int i = 0; i < frames.length; i++) {
                BufferedImage src = frames;
    ImageWriteParam iwp = iw.getDefaultWriteParam();
    IIOMetadata metadata = iw.getDefaultImageMetadata(
    new ImageTypeSpecifier(src), null);
    System.out.println("IIOMetadata: " + metadata);
    metadata.mergeTree(metadata.getNativeMetadataFormatName(), root);
    IIOImage ii = new IIOImage(src, null, metadata);
    iw.writeToSequence(ii, (ImageWriteParam) null);
    iw.endWriteSequence();
    ios.close();
    return file;
    public static void main(String[] args) throws Exception {
    // uncomment the other two if you like, but we can
    // see it work or fail with just the first and last.
    String[] names = {
    "bronze",
    //"silver",
    //"gold",
    "platinum"
    String pre = "http://forums.sun.com/im/";
    String suff = "-star.gif";
    BufferedImage[] frames = new BufferedImage[names.length];
    for (int ii = 0; ii < names.length; ii++) {
    URL url = new URL(pre + names[ii] + suff);
    System.out.println(url);
    frames[ii] = ImageIO.read(url);
    File f = saveAnimate(frames, "animatedstars", "500");
    JOptionPane.showMessageDialog(null, new ImageIcon(f.toURI().toURL()));
    Desktop.getDesktop().open(f);
    ImageInputStream iis = ImageIO.createImageInputStream(f);
    //System.out.println("ImageReader: " + ir1);
    //System.out.println("IIOMetadata: " + ir1.getStreamMetadata());
    Iterator itReaders = ImageIO.getImageReaders(iis);
    while (itReaders.hasNext()) {
    ImageReader ir = (ImageReader) itReaders.next();
    System.out.println("ImageReader: " + ir);
    System.out.println("IIOMetadata: " + ir.getStreamMetadata());

  • Set frame delay time for animated gif using ImageIO

    I'm trying to change the delay time of each frame for an animated gif by changing the metadata for each frame as following but it doesn't change anything.
    static private IIOMetadata setMetadata(IIOMetadata metadata, int delayMS) throws IOException
              Node root = metadata.getAsTree("javax_imageio_gif_image_1.0");
              for (Node c = root.getFirstChild(); c != null; c = c.getNextSibling())
                   String name = c.getNodeName();
                   if (c instanceof IIOMetadataNode)
                        IIOMetadataNode metaNode = (IIOMetadataNode) c;
                        if ("GraphicControlExtension".equals(name))
                             metaNode.setAttribute("delayTime", Integer.toString(delayMS));
         }Does anyone know how to set delay time for animated gif using ImageIO ?

    I'm trying to change the delay time of each frame for an animated gif by changing the metadata for each frame as following but it doesn't change anything.
    static private IIOMetadata setMetadata(IIOMetadata metadata, int delayMS) throws IOException
              Node root = metadata.getAsTree("javax_imageio_gif_image_1.0");
              for (Node c = root.getFirstChild(); c != null; c = c.getNextSibling())
                   String name = c.getNodeName();
                   if (c instanceof IIOMetadataNode)
                        IIOMetadataNode metaNode = (IIOMetadataNode) c;
                        if ("GraphicControlExtension".equals(name))
                             metaNode.setAttribute("delayTime", Integer.toString(delayMS));
         }Does anyone know how to set delay time for animated gif using ImageIO ?

  • How to save info in a meta-data of a jpg file?

    hi, i need to know how to save info in a meta-data of a jpg file:
    this is my code (doesn't work):
    i get an exception,
    javax.imageio.metadata.IIOInvalidTreeException: JPEGvariety and markerSequence nodes must be present
    at com.sun.imageio.plugins.jpeg.JPEGMetadata.mergeNativeTree(JPEGMetadata.java:1088)
    at com.sun.imageio.plugins.jpeg.JPEGMetadata.mergeTree(JPEGMetadata.java:1061)
    at playaround.IIOMetaDataWriter.run(IIOMetaDataWriter.java:59)
    at playaround.Main.main(Main.java:14)
    package playaround;
    import java.io.*;
    import java.util.Iterator;
    import java.util.Locale;
    import javax.imageio.*;
    import javax.imageio.metadata.IIOMetadata;
    import javax.imageio.metadata.IIOMetadataNode;
    import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
    import javax.imageio.stream.*;
    import org.w3c.dom.*;
    public class IIOMetaDataWriter {
    public static void run(String[] args) throws IOException{
    try {
    File f = new File("C:/images.jpg");
    ImageInputStream ios = ImageIO.createImageInputStream(f);
    Iterator readers = ImageIO.getImageReaders(ios);
    ImageReader reader = (ImageReader) readers.next();
    reader.setInput(ImageIO.createImageInputStream(f));
    ImageWriter writer = ImageIO.getImageWriter(reader);
    writer.setOutput(ImageIO.createImageOutputStream(f));
    JPEGImageWriteParam param = new JPEGImageWriteParam(Locale.getDefault());
    IIOMetadata metaData = writer.getDefaultStreamMetadata(param);
    String MetadataFormatName = metaData.getNativeMetadataFormatName();
    IIOMetadataNode root = (IIOMetadataNode)metaData.getAsTree(MetadataFormatName);
    IIOMetadataNode markerSequence = getChildNode(root, "markerSequence");
    if (markerSequence == null) {
    markerSequence = new IIOMetadataNode("JPEGvariety");
    root.appendChild(markerSequence);
    IIOMetadataNode jv = getChildNode(root, "JPEGvariety");
    if (jv == null) {
    jv = new IIOMetadataNode("JPEGvariety");
    root.appendChild(jv);
    IIOMetadataNode child = getChildNode(jv, "myNode");
    if (child == null) {
    child = new IIOMetadataNode("myNode");
    jv.appendChild(child);
    child.setAttribute("myAttName", "myAttValue");
    metaData.mergeTree(MetadataFormatName, root);
    catch (Throwable t){
    t.printStackTrace();
    protected static IIOMetadataNode getChildNode(Node n, String name) {
    NodeList nodes = n.getChildNodes();
    for (int i = 0; i < nodes.getLength(); i++) {
    Node child = nodes.item(i);
    if (name.equals(child.getNodeName())) {
    return (IIOMetadataNode)child;
    return null;
    static void displayMetadata(Node node, int level) {
    indent(level); // emit open tag
    System.out.print("<" + node.getNodeName());
    NamedNodeMap map = node.getAttributes();
    if (map != null) { // print attribute values
    int length = map.getLength();
    for (int i = 0; i < length; i++) {
    Node attr = map.item(i);
    System.out.print(" " + attr.getNodeName() +
    "=\"" + attr.getNodeValue() + "\"");
    Node child = node.getFirstChild();
    if (child != null) {
    System.out.println(">"); // close current tag
    while (child != null) { // emit child tags recursively
    displayMetadata(child, level + 1);
    child = child.getNextSibling();
    indent(level); // emit close tag
    System.out.println("</" + node.getNodeName() + ">");
    } else {
    System.out.println("/>");
    static void indent(int level) {
    for (int i = 0; i < level; i++) {
    System.out.print(" ");
    }

    Hi,
    Yes, you need store data to table, and fetch it when page is opened.
    Simple way is create table with few columns and e.g. with CLOB column and then create form based on that table.
    Then modify item types as you like, e.g. use HTML editor for CLOB column
    Regards,
    Jari

  • Server goes out of memory when annotating TIFF File. Help with Tiled Images

    I am new to JAI and have a problem with the system going out of memory
    Objective:
    1)Load up a TIFF file (each approx 5- 8 MB when compressed with CCITT.6 compression)
    2)Annotate image (consider it as a simple drawString with the Graphics2D object of the RenderedImage)
    3)Send it to the servlet outputStream
    Problem:
    Server goes out of memory when 5 threads try to access it concurrently
    Runtime conditions:
    VM param set to -Xmx1024m
    Observation
    Writing the files takes a lot of time when compared to reading the files
    Some more information
    1)I need to do the annotating at a pre-defined specific positions on the images(ex: in the first quadrant, or may be in the second quadrant).
    2)I know that using the TiledImage class its possible to load up a portion of the image and process it.
    Things I need help with:
    I do not know how to send the whole file back to servlet output stream after annotating a tile of the image.
    If write the tiled image back to a file, or to the outputstream, it gives me only the portion of the tile I read in and watermarked, not the whole image file
    I have attached the code I use when I load up the whole image
    Could somebody please help with the TiledImage solution?
    Thx
    public void annotateFile(File file, String wText, OutputStream out, AnnotationParameter param) throws Throwable {
    ImageReader imgReader = null;
    ImageWriter imgWriter = null;
    TiledImage in_image = null, out_image = null;
    IIOMetadata metadata = null;
    ImageOutputStream ios = null;
    try {
    Iterator readIter = ImageIO.getImageReadersBySuffix("tif");
    imgReader = (ImageReader) readIter.next();
    imgReader.setInput(ImageIO.createImageInputStream(file));
    metadata = imgReader.getImageMetadata(0);
    in_image = new TiledImage(JAI.create("fileload", file.getPath()), true);
    System.out.println("Image Read!");
    Annotater annotater = new Annotater(in_image);
    out_image = annotater.annotate(wText, param);
    Iterator writeIter = ImageIO.getImageWritersBySuffix("tif");
    if (writeIter.hasNext()) {
    imgWriter = (ImageWriter) writeIter.next();
    ios = ImageIO.createImageOutputStream(out);
    imgWriter.setOutput(ios);
    ImageWriteParam iwparam = imgWriter.getDefaultWriteParam();
    if (iwparam instanceof TIFFImageWriteParam) {
    iwparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    TIFFDirectory dir = (TIFFDirectory) out_image.getProperty("tiff_directory");
    double compressionParam = dir.getFieldAsDouble(BaselineTIFFTagSet.TAG_COMPRESSION);
    setTIFFCompression(iwparam, (int) compressionParam);
    else {
    iwparam.setCompressionMode(ImageWriteParam.MODE_COPY_FROM_METADATA);
    System.out.println("Trying to write Image ....");
    imgWriter.write(null, new IIOImage(out_image, null, metadata), iwparam);
    System.out.println("Image written....");
    finally {
    if (imgWriter != null)
    imgWriter.dispose();
    if (imgReader != null)
    imgReader.dispose();
    if (ios != null) {
    ios.flush();
    ios.close();
    }

    user8684061 wrote:
    U are right, SGA is too large for my server.
    I guess oracle set SGA automaticlly while i choose default installion , but ,why SGA would be so big? Is oracle not smart enough ?Default database configuration is going to reserve 40% of physical memory for SGA for an instance, which you as a user can always change. I don't see anything wrong with that to say Oracle is not smart.
    If i don't disincrease SGA, but increase max-shm-memory, would it work?This needs support from the CPU architecture (32 bit or 64 bit) and the kernel as well. Read more about the huge pages.

  • How to get the Summary details of jpg file like (title, subject, author)

    Hi All,
    Plz help me out of this Reading Windows file summary properties (title, subject, author) in Java.
    When select properties giing right click on the file after that window open with the three tabs containg General,Security,Summary.
    From the Summary tab i need to pull the data (title, subject, author) using Java api.
    Regards
    Ramesh

    I tried many ways using ImageIO, ImageReader
    ImageInputStream inStream = ImageIO.createImageInputStream(new File("E:\\Ramesh\\Blue hills.jpg"));
                   Iterator<ImageReader> imgItr = ImageIO.getImageReaders(inStream);
                   while (imgItr.hasNext())
                        ImageReader reader = imgItr.next();
                        reader.setInput(inStream, true);
                   String fm = reader.getFormatName();
                   System.out.println("format name : " + fm );
                   Raster raster = reader.readRaster(0, null);
                        IIOMetadata metadata = reader.getImageMetadata(0);
                        reader.getOriginatingProvider();
                        String[] names = metadata.getMetadataFormatNames();
                        int length = names.length;
                        for (int i = 0; i < length; i++)
                             System.out.println( "Format name: " + names[ i ] );
                        }

  • ICC profile to convert RGB to CMYK,   jpeg is ok, png format have a problem

    When I use ICC profile to convert RGB to CMYK, jpeg format is ok, but png format have a problem.the color is lossy.
    It means, the png file color is shallow than jpeg file after convert.Could anybody help me?
    thanks
    source code
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.util.Iterator;
    import javax.imageio.IIOImage;
    import javax.imageio.ImageIO;
    import javax.imageio.ImageTypeSpecifier;
    import javax.imageio.ImageWriteParam;
    import javax.imageio.ImageWriter;
    import javax.imageio.metadata.IIOMetadata;
    import javax.imageio.metadata.IIOMetadataNode;
    import javax.imageio.stream.ImageOutputStream;
    import org.w3c.dom.Node;
    import com.sun.image.codec.jpeg.ImageFormatException;
    import com.sun.image.codec.jpeg.JPEGCodec;
    import com.sun.image.codec.jpeg.JPEGEncodeParam;
    import com.sun.image.codec.jpeg.JPEGImageEncoder;
    public class TestImage {
         public static void main(String args[]) throws ImageFormatException, IOException{
              BufferedImage readImage = null;
              try {
                  readImage = ImageIO.read(new File("C:\\TEST.jpg"));
              } catch (Exception e) {
                  e.printStackTrace();
                  readImage = null;
              readImage = CMYKProfile.getInstance().doChColor(readImage);
              writeImage(readImage, "C:\\TEST_after_.jpg", 1.0f);
        protected static String getSuffix(String filename) {
            int i = filename.lastIndexOf('.');
            if(i>0 && i<filename.length()-1) {
                return filename.substring(i+1).toLowerCase();
            return "";
        protected static void writeImage(BufferedImage image, String filename, float quality) {
            Iterator writers = ImageIO.getImageWritersBySuffix(getSuffix(filename));
            System.out.println("filename�F"+filename);
            if (writers.hasNext()) {
                ImageWriter writer = (ImageWriter)writers.next();
                try {
                    ImageOutputStream stream
                        = ImageIO.createImageOutputStream(new File(filename));
                    writer.setOutput(stream);
                    ImageWriteParam param = writer.getDefaultWriteParam();
                    if (param.canWriteCompressed()) {
                        param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);//NO COMPRESS
                        param.setCompressionQuality(quality);
                    } else {
                        System.out.println("Compression is not supported.");
                    IIOMetadata metadata = null;
                    if(getSuffix(filename).equals("png") || getSuffix(filename).equals("PNG")){
                         ImageTypeSpecifier imageTypeSpecifier = new ImageTypeSpecifier(image);
                         metadata = writer.getDefaultImageMetadata(imageTypeSpecifier, param);
                            String sFormat = "javax_imageio_png_1.0";
                            Node node = metadata.getAsTree(sFormat);
                            IIOMetadataNode gammaNode = new IIOMetadataNode("gAMA");
                            String sGamma = "55556";
                            gammaNode.setAttribute("value", sGamma);
                            node.appendChild(gammaNode);
                            metadata.setFromTree(sFormat, node);
                    writer.write(null, new IIOImage(image, null, metadata), param);
                    writer.dispose();
                    return;
                } catch (IOException ex) {
                    ex.printStackTrace();
    }

    Hi,
    I am having similar problems. I have read somewhere that png format can not handle CMYK colorspace anyway, which I find odd (and plainly stupid IM(NS)HO) which would mean that converting to RGB and therefore using profiles is mandatory.
    May be you should check if the internal format of the png files claims it is RGB or CMYK (using ImageMagick's "identify" command for example).
    HTH
    JG

  • Reading all the Exif data from TIFF Image

    Hi!
    I am trying to get Exif information out of an image. I succeeded partly because I get The Baseline (EXIF IFD0) and EXIF Sub IFD, but not the rest (The Maker Note, EXIF Interoperability IFD and IFD1). Can anyone tell me what I could try to get all the data out. Any help is appiciated
    URL url = new URL(paramName);
    ImageInputStream stream = ImageIO.createImageInputStream(url.openStream());
            Iterator iter = ImageIO.getImageReaders(stream);
            ImageReader reader = (ImageReader) iter.next();
            reader.setInput(stream);
            BufferedImage image = reader.read(0);
            IIOMetadata metadata = reader.getImageMetadata(0);
            org.w3c.dom.Node metadataRoot = metadata.getAsTree(metadata.getNativeMetadataFormatName());
            DOMSource doc = new DOMSource(metadataRoot);
            return doc;

    There is a separate one for Firefox, but it appears to only be compatible with Firefox versions 0.7-3.0.x, so Opanda has not made it compatible with Firefox 3.5.x and 3.6.x versions, I suppose:
    http://www.opanda.com/en/download/
    See this and the link in that post for a possible solution: http://forums.steves-digicams.com/1048665-post6.html

  • Converting cmyk compressed images to rgb compressed format

    Hi,
    I need some help in converting of CMYK images to RGB images. I got some sample code from internet but I get some run time exceptions with that and I'm not able to figure out the reason for the same. Pls help me in fixing the same. Any help will be sincerely appreicated.
    The code is given below :
    import java.awt.image.*;
    import java.awt.image.renderable.*;
    import java.awt.color.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.io.*;
    import java.net.*;
    import javax.media.jai.*;
    import com.sun.image.codec.jpeg.*;
    public class CMYKTest1 {
      public static void main(String args[]) throws Exception{
         RenderedOp op = JAI.create("fileload", "Kristopher Brock LOGO.jpg");
         ColorModel rgbcm = op.getColorModel();
         ICC_Profile profile = ICC_Profile.getInstance("CMYK.pf");
    //     ICC_Profile profile = ICC_Profile.getInstance(ColorSpace.TYPE_CMYK);
         ICC_ColorSpace icp = new ICC_ColorSpace(profile);
         ColorModel colorModel =
              RasterFactory.createComponentColorModel(op.getSampleModel().getDataType(),
                                                                icp,
                                                                false,
                                                                false,
                                                                Transparency.OPAQUE);
         ImageLayout il = new ImageLayout();
         il.setSampleModel(colorModel.createCompatibleSampleModel(op.getWidth(),
                                                                                op.getHeight()));
         RenderingHints hints = new RenderingHints(JAI.KEY_IMAGE_LAYOUT, il);
         ParameterBlock pb = new ParameterBlock();
         pb.addSource(op).add(colorModel);
         op = JAI.create("ColorConvert", pb, hints);
         pb = new ParameterBlock();
         pb.addSource(op).add(rgbcm);
         il = new ImageLayout();
         il.setSampleModel(rgbcm.createCompatibleSampleModel(op.getWidth(),
                                                                          op.getHeight()));
         hints = new RenderingHints(JAI.KEY_IMAGE_LAYOUT, il);
         op = JAI.create("ColorConvert", pb, hints);
         JAI.create("filestore", op, "earthrgb.jpg", "JPEG", null);
         BufferedImage img = op.getAsBufferedImage(null, null);
         OutputStream fout = new FileOutputStream("earthrgb1.jpg");
         JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fout);
         JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(img);
         param.setQuality(1, false);
         param.setXDensity(300);
         param.setYDensity(400);
         encoder.encode(img, param);
         fout.close();
    }I get the following error:
    Caused by: java.lang.IllegalArgumentException: Numbers of source Raster bands and source color space components do not match
         at java.awt.image.ColorConvertOp.filter(Unknown Source)
         at com.sun.media.jai.opimage.ColorConvertOpImage.computeRectNonColorSpaceJAI(ColorConvertOpImage.java:373)
         at com.sun.media.jai.opimage.ColorConvertOpImage.computeRect(ColorConvertOpImage.java:290)
         at javax.media.jai.PointOpImage.computeTile(PointOpImage.java:914)
         at com.sun.media.jai.util.SunTileScheduler.scheduleTile(SunTileScheduler.java:904)
         at javax.media.jai.OpImage.getTile(OpImage.java:1129)
         at javax.media.jai.PointOpImage.computeTile(PointOpImage.java:911)
         at com.sun.media.jai.util.SunTileScheduler.scheduleTile(SunTileScheduler.java:904)
         at javax.media.jai.OpImage.getTile(OpImage.java:1129)
         at com.sun.media.jai.codecimpl.JPEGImageEncoder.encode(JPEGImageEncoder.java:173)
         at com.sun.media.jai.opimage.EncodeRIF.create(EncodeRIF.java:70)
         ... 24 more
    Error: One factory fails for the operation "filestore"
    Occurs in: javax.media.jai.ThreadSafeOperationRegistry
    java.lang.reflect.InvocationTargetException
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
         at java.lang.reflect.Method.invoke(Unknown Source)
         at javax.media.jai.FactoryCache.invoke(FactoryCache.java:122)
         at javax.media.jai.OperationRegistry.invokeFactory(OperationRegistry.java:1674)
         at javax.media.jai.ThreadSafeOperationRegistry.invokeFactory(ThreadSafeOperationRegistry.java:473)
         at javax.media.jai.registry.RIFRegistry.create(RIFRegistry.java:332)
         at javax.media.jai.RenderedOp.createInstance(RenderedOp.java:819)
         at javax.media.jai.RenderedOp.createRendering(RenderedOp.java:867)
         at javax.media.jai.RenderedOp.getRendering(RenderedOp.java:888)
         at javax.media.jai.JAI.createNS(JAI.java:1099)
         at javax.media.jai.JAI.create(JAI.java:973)
         at javax.media.jai.JAI.create(JAI.java:1668)
         at CMYKTest1.main(CMYKTest1.java:79)
    Caused by: javax.media.jai.util.ImagingException: All factories fail for the operation "encode"
         at javax.media.jai.OperationRegistry.invokeFactory(OperationRegistry.java:1687)
         at javax.media.jai.ThreadSafeOperationRegistry.invokeFactory(ThreadSafeOperationRegistry.java:473)
         at javax.media.jai.registry.RIFRegistry.create(RIFRegistry.java:332)
         at com.sun.media.jai.opimage.FileStoreRIF.create(FileStoreRIF.java:138)
         ... 15 moreThanks & Regards,
    Magesh.

    The following code converts an cmyk jpeg image into an rgb jpeg image.
    The only problem if this code is that it loads the whole image in memory and thus you'll need a lot of RAM when converting large images. For example, it take around 300 MB to convert a 3000*3800px image (this is a 5MB jpeg image when compressed on disk).
    import com.sun.image.codec.jpeg.JPEGImageEncoder;
    import com.sun.image.codec.jpeg.JPEGCodec;
    import com.sun.image.codec.jpeg.JPEGEncodeParam;
    import javax.imageio.ImageIO;
    import javax.imageio.ImageReader;
    import javax.imageio.stream.ImageInputStream;
    import javax.imageio.metadata.IIOMetadata;
    import javax.imageio.metadata.IIOMetadataNode;
    import java.util.*;
    import java.io.*;
    import java.awt.image.*;
    import java.awt.*;
    import java.awt.color.ColorSpace;
    import org.w3c.dom.NodeList;
    public class Test {
        public static void main(String[] args) throws Exception {
            BufferedImage i1 = readImage(new File("cmyk.jpg"));
            BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File("rgb.jpg")));
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(i1);
            param.setQuality(1, false);
            encoder.setJPEGEncodeParam(param);
            encoder.encode(i1);
        public Test() {
        // extract metadata
        public static BufferedImage readImage(File file) throws IOException {
            // Get an ImageReader.
            ImageInputStream input = ImageIO.createImageInputStream(file);
            Iterator readers = ImageIO.getImageReaders(input);
            if (readers == null || !readers.hasNext()) {
                throw new RuntimeException("No ImageReaders found");
            ImageReader reader = (ImageReader) readers.next();
            reader.setInput(input);
            String format = reader.getFormatName();
            if ("JPEG".equalsIgnoreCase(format) || "JPG".equalsIgnoreCase(format)) {
                IIOMetadata metadata = reader.getImageMetadata(0);
                String metadataFormat = metadata.getNativeMetadataFormatName();
                IIOMetadataNode iioNode = (IIOMetadataNode) metadata.getAsTree(metadataFormat);
                NodeList children = iioNode.getElementsByTagName("app14Adobe");
                if (children.getLength() > 0) {
                    iioNode = (IIOMetadataNode) children.item(0);
                    int transform = Integer.parseInt(iioNode.getAttribute("transform"));
                    Raster raster = reader.readRaster(0, reader.getDefaultReadParam());
                    if (input != null) {
                        input.close();
                    reader.dispose();
                    return createJPEG4(raster, transform);
            throw new RuntimeException("No ImageReaders found");
         * Java's ImageIO can't process 4-component
         * images
         * <p/>
         * and Java2D can't apply AffineTransformOp
         * either,
         * <p/>
         * so convert raster data to
         * RGB.
         * <p/>
         * Technique due to MArk
         * Stephens.
         * <p/>
         * Free for any
         * use.
        private static BufferedImage createJPEG4(Raster raster, int xform) {
            int w = raster.getWidth();
            int h = raster.getHeight();
            byte[] rgb = new byte[w * h * 3];
            // if (Adobe_APP14 and transform==2) then YCCK else CMYK
            if (xform == 2) {    // YCCK -- Adobe
                float[] Y = raster.getSamples(0, 0, w, h, 0, (float[]) null);
                float[] Cb = raster.getSamples(0, 0, w, h, 1, (float[]) null);
                float[] Cr = raster.getSamples(0, 0, w, h, 2, (float[]) null);
                float[] K = raster.getSamples(0, 0, w, h, 3, (float[]) null);
                for (int i = 0, imax = Y.length, base = 0; i < imax; i++, base += 3) {
                    float k = 220 - K, y = 255 - Y[i], cb = 255 - Cb[i], cr = 255 - Cr[i];
    double val = y + 1.402 * (cr - 128) - k;
    val = (val - 128) * .65f + 128;
    rgb[base] = val < 0.0 ? (byte) 0 : val > 255.0 ? (byte) 0xff : (byte) (val + 0.5);
    val = y - 0.34414 * (cb - 128) - 0.71414 * (cr - 128) - k;
    val = (val - 128) * .65f + 128;
    rgb[base + 1] = val < 0.0 ? (byte) 0 : val > 255.0 ? (byte) 0xff : (byte) (val + 0.5);
    val = y + 1.772 * (cb - 128) - k;
    val = (val - 128) * .65f + 128;
    rgb[base + 2] = val < 0.0 ? (byte) 0 : val > 255.0 ? (byte) 0xff : (byte) (val + 0.5);
    else {
    // assert xform==0: xform;
    // CMYK
    int[] C = raster.getSamples(0, 0, w, h, 0, (int[]) null);
    int[] M = raster.getSamples(0, 0, w, h, 1, (int[]) null);
    int[] Y = raster.getSamples(0, 0, w, h, 2, (int[]) null);
    int[] K = raster.getSamples(0, 0, w, h, 3, (int[]) null);
    for (int i = 0, imax = C.length, base = 0; i < imax; i++, base += 3) {
    int c = 255 - C[i];
    int m = 255 - M[i];
    int y = 255 - Y[i];
    int k = 255 - K[i];
    float kk = k / 255f;
    rgb[base] = (byte) (255 - Math.min(255f, c * kk + k));
    rgb[base + 1] = (byte) (255 - Math.min(255f, m * kk + k));
    rgb[base + 2] = (byte) (255 - Math.min(255f, y * kk + k));
    // from other image types we know InterleavedRaster's can be
    // manipulated by AffineTransformOp, so create one of
    // those.
    raster = Raster.createInterleavedRaster(new DataBufferByte(rgb, rgb.length), w, h, w * 3, 3, new int[]{0, 1, 2}, null);
    ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
    ColorModel cm = new ComponentColorModel(cs, false, true, Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
    return new BufferedImage(cm, (WritableRaster) raster, true, null);

  • ImageWriter and ByteArrayOutputStream problem

    I am working with multipage images and there's bizzare problem I stumbled on regarding, I guess, flushing streams
    When I use ByteArrayOutputStream then ImageWriter writes only 146 bytes to it. When I use FileOutputStream
    It works fine.
    Here's my code snippet (FileUtils is a class is from org.apache.commons.lang)
                    ByteArrayInputStream bais = new ByteArrayInputStream(FileUtils.readFileToByteArray(f));
                    ByteArrayOutputStream baos = new ByteArrayOutputStream(bais.available());
                    ImageInputStream iis = ImageIO.createImageInputStream(bais);
                    tiffReader.setInput(iis);
                    ImageOutputStream ios = ImageIO.createImageOutputStream(baos);
                    tiffWriter.setOutput(ios);
                    TIFFImageWriteParam param = new TIFFImageWriteParam(Locale.US); // (TIFFImageWriteParam) tiffWriter.getDefaultWriteParam();
                    param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
                    param.setCompressionType("CCITT T.6");
                    //System.out.println("PhotoInterp = " + param.getPhotometricInterpretation());
                    int page = 0;
                    tiffWriter.prepareWriteSequence(tiffReader.getStreamMetadata());
                    while(true) {
                        try {
                            IIOMetadata metadata = tiffReader.getImageMetadata(page);
                            BufferedImage img = tiffReader.read(page);
                            //tiffWriter.writeToSequence(new IIOImage(img,null,metadata),param);
                            tiffWriter.writeToSequence(new IIOImage(img,null,null), param);
                            //tiffWriter.writeInsert(page, new IIOImage(img,null,null),param);
                            page++;
                            //ios.flush();
                        }catch(IndexOutOfBoundsException e) {
                            // all pages done
                            break;
                    tiffWriter.endWriteSequence();
                    ios.flush();
                    FileUtils.writeByteArrayToFile(new File(devDir, newName), baos.toByteArray());

    If i remark second part of code and open first part of code that is not working
    public String GPS() {
    String NMEA = "";
    try {
    int ch;
    boolean beg = false;
    String Answer = "";
    byte[] buffer = new byte[512];
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    while ( (ch = inStream.read(buffer)) != -1) {
    bout.write(buffer, 0, ch);
    NMEA = bout.toString();
    bout.flush();
    bout.close();
    /* while (inStream.available()>0) {
    if (inStream.available() > 0) {
    ch = inStream.read();
    if (ch == 0x24) {
    beg = true;
    if (ch == 0x2A) {
    beg = false;
    if (Answer.indexOf("GPRMC") >= 0) {
    NMEA = Answer;
    Answer = "";
    if ( (beg) & (ch != 0x24)) {
    Answer = Answer + (char) ch;
    catch (Exception e) {
    try {
    // InitGPRSConnectionUDP(e.getMessage());
    sendline(e.getMessage());
    catch (Exception r) {
    return NMEA;
    but If i remark first part of code and open second code that is working. I have packet from test sending from pc.
    public String GPS() {
    String NMEA = "";
    try {
    int ch;
    boolean beg = false;
    String Answer = "";
    /* byte[] buffer = new byte[512];
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    while ( (ch = inStream.read(buffer)) != -1) {
    bout.write(buffer, 0, ch);
    NMEA = bout.toString();
    bout.flush();
    bout.close();
    while (inStream.available()>0) {
    if (inStream.available() > 0) {
    ch = inStream.read();
    if (ch == 0x24) {
    beg = true;
    if (ch == 0x2A) {
    beg = false;
    if (Answer.indexOf("GPRMC") >= 0) {
    NMEA = Answer;
    Answer = "";
    if ( (beg) & (ch != 0x24)) {
    Answer = Answer + (char) ch;
    catch (Exception e) {
    try {
    catch (Exception r) {
    return NMEA;
    Edited by: TC65 on Jan 15, 2008 10:19 AM

  • ImageIO encode split page with original params?

    Hey all,
    I'm working with TIFF's and the ImageIO library. I split out a single page from a TIFF and then re-encode it, but I can not figure out how to re-encode with the exact same configuration of the original TIFF (i.e. compression, resolution, white/black, etc.).
    Is there some way to do this please? Attached is my working code if this helps!
    -D
         Iterator writers = javax.imageio.ImageIO.getImageWritersByFormatName("tiff");
         javax.imageio.ImageWriter writer = (javax.imageio.ImageWriter)writers.next();
         ByteArrayOutputStream out = new ByteArrayOutputStream();
         javax.imageio.stream.ImageOutputStream ios = javax.imageio.ImageIO.createImageOutputStream(out);
         ImageReadParam rparam = imageReader.getDefaultReadParam();
         TIFFImageWriteParam writeParam = (TIFFImageWriteParam)writer.getDefaultWriteParam();
         writer.setOutput(ios);
         writer.write(iiometadata,iioimage,writeParam);
         ios.flush();
         return out.toByteArray();

    I'll answer my own question. Key is to copy and/or edit the Node object representing the image's metadata. This is an XML representation of the TIFF tags.
    In this example, all the input images properties are encoding in the output image.
                ImageReader reader ...
                ImageWriter writer ...
                BufferedImage bi = reader.read(0);
                IIOMetadata metaData = reader.getImageMetadata(0);
                Node node = metaData.getAsTree("com_sun_media_imageio_plugins_tiff_image_1.0");
                ImageOutputStream ios = ImageIO.createImageOutputStream(target);
                writer.setOutput(ios);
                IIOMetadata imageMetadata = writer.getDefaultImageMetadata(null, writeParam);
                imageMetadata.setFromTree("com_sun_media_imageio_plugins_tiff_image_1.0", node);
                IIOImage img = new IIOImage(bi, null, imageMetadata);
                writer.write(null, img, writeParam);

  • Capture Image metadata with JAI

    Hi,
    Can we capture the metadata of a photograph taken by a digital camera (JPEG file) using the JAI?
    Some of the features that I'm interested in capturing are: Data Picture Taken, Camera Model and so on.
    Any sample snippet of code is highly appreciated.
    Thanks,
    Bhaskar

    Should have searched the forum throughly....this is the code which was given by Mr. Maxideon [http://forums.sun.com/profile.jspa?userID=1078315] -- All credits to him -- although this post is very old, probably would be helpful for someone else :)
    import javax.swing.*;
    import javax.imageio.*;
    import javax.imageio.metadata.*;
    import javax.imageio.stream.ImageInputStream;
    import javax.imageio.stream.MemoryCacheImageInputStream;
    import org.w3c.dom.NodeList;
    public class ExifSSCCE {
        private static String JPEGMetaFormat = "javax_imageio_jpeg_image_1.0";
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    try{
                        runSequence();
                    }catch(Exception e) {
                       e.printStackTrace();
                       System.exit(-1);
        private static void showMessageAndExit(String message) {
            JOptionPane.showMessageDialog(null,message,"Error",JOptionPane.ERROR_MESSAGE);
            System.exit(0);
        public static void runSequence() throws java.io.IOException{
            if(!ImageIO.getImageReadersByFormatName("tif").hasNext()) {
                showMessageAndExit("You will need a tiff ImageReader plugin to " +
                        "parse exif data.  Please download \"JAI-ImageIO\".");
            JOptionPane.showMessageDialog(null,"Please select a jpeg file with " +
                    "EXIF metadata");
            JFileChooser chooser = new JFileChooser();
            if(chooser.showOpenDialog(chooser) == JFileChooser.CANCEL_OPTION) {
                System.exit(0);
            java.io.File toOpen = chooser.getSelectedFile();
            ImageInputStream in = ImageIO.createImageInputStream(toOpen);
            java.util.Iterator<ImageReader> readers = ImageIO.getImageReaders(in);
            if(!readers.hasNext()) {
                showMessageAndExit("The selected file was not an image file, or " +
                        "not a type that ImageIO recognized.");
            ImageReader reader = null;
            while(readers.hasNext()) {
                ImageReader tmp = readers.next();
                if(JPEGMetaFormat.equals(tmp.getOriginatingProvider().getNativeImageMetadataFormatName())) {
                    reader = tmp;
                    break;
            if(reader == null) {
                showMessageAndExit("The selected file was not a jpeg file.");
            reader.setInput(in, true, false);
            byte[] exifRAW = getEXIF(reader.getImageMetadata(0));
            if(exifRAW == null) {
                showMessageAndExit("The selected jpeg file did not contain any " +
                        "exif data.");
            reader.dispose();
            in.close();
            IIOMetadata exifMeta = getTiffMetaFromEXIF(exifRAW);
            JFrame frame = new JFrame();
            frame.setContentPane(new JScrollPane(parseExifMeta(exifMeta)));
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setVisible(true);
        private static JTable parseExifMeta(IIOMetadata exifMeta) {
            //Specification of "com_sun_media_imageio_plugins_tiff_image_1.0"
            //http://download.java.net/media/jai-imageio/javadoc/1.1/com/sun/media/imageio/plugins/tiff/package-summary.html
            javax.swing.table.DefaultTableModel tags =
                    new javax.swing.table.DefaultTableModel();
            tags.addColumn("Tag #");
            tags.addColumn("Name");
            tags.addColumn("Value(s)");
            IIOMetadataNode root = (IIOMetadataNode)
                    exifMeta.getAsTree("com_sun_media_imageio_plugins_tiff_image_1.0");
            NodeList imageDirectories = root.getElementsByTagName("TIFFIFD");
            for(int i = 0; i < imageDirectories.getLength(); i++) {
                IIOMetadataNode directory = (IIOMetadataNode) imageDirectories.item(i);
                NodeList tiffTags = directory.getElementsByTagName("TIFFField");
                for(int j = 0; j < tiffTags.getLength(); j++) {
                    IIOMetadataNode tag = (IIOMetadataNode) tiffTags.item(j);
                    String tagNumber = tag.getAttribute("number");
                    String tagName   = tag.getAttribute("name");
                    String tagValue;
                    StringBuilder tmp = new StringBuilder();
                    IIOMetadataNode values = (IIOMetadataNode) tag.getFirstChild();
                    if("TIFFUndefined".equals(values.getNodeName())) {
                        tmp.append(values.getAttribute("value"));
                    }else {
                        NodeList tiffNumbers = values.getChildNodes();
                        for(int k = 0; k < tiffNumbers.getLength(); k++) {
                            tmp.append(((IIOMetadataNode) tiffNumbers.item(k)).getAttribute("value"));
                            tmp.append(",");
                        tmp.deleteCharAt(tmp.length()-1);
                    tagValue = tmp.toString();
                    tags.addRow(new String[]{tagNumber,tagName,tagValue});
            return new JTable(tags);
        /**Returns the EXIF information from the given metadata if present.  The
         * metadata is assumed to be in <pre>javax_imageio_jpeg_image_1.0</pre> format.
         * If EXIF information was not present then null is returned.*/
        public static byte[] getEXIF(IIOMetadata meta) {
            //http://java.sun.com/javase/6/docs/api/javax/imageio/metadata/doc-files/jpeg_metadata.html
            //javax_imageio_jpeg_image_1.0
            //-->markerSequence
            //---->unknown (attribute: "MarkerTag" val: 225 (for exif))
            IIOMetadataNode root = (IIOMetadataNode) meta.getAsTree(JPEGMetaFormat);
            IIOMetadataNode markerSeq = (IIOMetadataNode)
                    root.getElementsByTagName("markerSequence").item(0);
            NodeList unkowns = markerSeq.getElementsByTagName("unknown");
            for(int i = 0; i < unkowns.getLength(); i++) {
                IIOMetadataNode marker = (IIOMetadataNode) unkowns.item(i);
                if("225".equals(marker.getAttribute("MarkerTag"))) {
                    return (byte[]) marker.getUserObject();
            return null;
        /**Uses a TIFFImageReader plugin to parse the given exif data into tiff
         * tags.  The returned IIOMetadata is in whatever format the tiff ImageIO
         * plugin uses.  If there is no tiff plugin, then this method returns null.*/
        public static IIOMetadata getTiffMetaFromEXIF(byte[] exif) {
            java.util.Iterator<ImageReader> readers =
                    ImageIO.getImageReadersByFormatName("tif");
            ImageReader reader;
            if(!readers.hasNext()) {
                return null;
            }else {
                reader = readers.next();
            //skip the 6 byte exif header
            ImageInputStream wrapper = new MemoryCacheImageInputStream(
                    new java.io.ByteArrayInputStream(exif,6,exif.length-6));
            reader.setInput(wrapper,true,false);
            IIOMetadata exifMeta;
            try {
                exifMeta = reader.getImageMetadata(0);
            }catch(Exception e) {
                //shouldn't happen
                throw new Error(e);
            reader.dispose();
            return exifMeta;
    }Edited by: amitahire on Mar 27, 2010 4:57 AM

  • Read Metadata from TIFF-file

    Hi All!
    I try to get metadata from a TIFF-file. I tried to do this with this code. Everytime i get the same error. Anyone can help me?
    int imageIndex = 0;
    File f = new File(sourceFile);
    ImageInputStream stream = ImageIO.createImageInputStream(f);
    Iterator iter = ImageIO.getImageReaders(stream);
    ImageReader reader = (ImageReader)iter.next();
    reader.setInput(stream);
    IIOMetadata m = reader.getImageMetadata(imageIndex);
    Errormessage:
    run-single:
    Exception in thread "main" javax.imageio.IIOException: I/O error reading image metadata!
    at com.sun.media.imageioimpl.plugins.tiff.TIFFImageReader.readMetadata(Unknown Source)
    at com.sun.media.imageioimpl.plugins.tiff.TIFFImageReader.seekToImage(Unknown Source)
    at com.sun.media.imageioimpl.plugins.tiff.TIFFImageReader.getImageMetadata(Unknown Source)
    at tiffmetadatabug.Main.main(Main.java:80)
    Caused by: java.io.EOFException
    at javax.imageio.stream.ImageInputStreamImpl.readShort(ImageInputStreamImpl.java:211)
    at javax.imageio.stream.ImageInputStreamImpl.readUnsignedShort(ImageInputStreamImpl.java:222)
    at com.sun.media.imageioimpl.plugins.tiff.TIFFIFD.initialize(Unknown Source)
    at com.sun.media.imageioimpl.plugins.tiff.TIFFIFD.initialize(Unknown Source)
    at com.sun.media.imageioimpl.plugins.tiff.TIFFImageMetadata.initializeFromStream(Unknown Source)
    ... 4 more
    Java Result: 1

    I think you should test this with one or two pictures - import/convert, save metadata to file, geotag, read metadata. Also try import/convert, make small adjustment, save metadata to file, geotag, read metadata. In iView I often write metadata to DNG's that have been adjusted, then read the metadata in Lightroom - sometimes I add more data in iView and do more adjustments.
    I have seen the problem you describe, but it has been with raw files which I have adjusted in Lightroom but haven't saved out the metadata. I have then created an xmp sidecar in iView, and read the metadata in LR. So the sidecar had no ACR/LR instructions. The result was that my adjustments were wiped out. What I suspect is that something similar is happening with your DNGs - that conversion creates them but doesn't write the ACR/LR fields.
    So try a few alternative sequences.
    John

Maybe you are looking for

  • Ringtones for iphone 5

    can you select ringtones for iphone 5 for Verizon Wireless

  • Block sliding columns in a grid

    Hi all, can anyone please explain me how i can block the sliding columns in a grid. For example, i have a grid with 20 columns and i need to block (when i use the horizontal scrollbar) the first 4 columns. Thank a lot to everyone. I use SAP Business

  • Windows 7 Permissions

    I have a file on my Windows 7 desktop (a game file that I transfered off a flash drive) that I cannot delete. I am signed into the only account (named 'Ryan') that I have set up on this OS. The file shows full permissions given to Ryan. When I drag t

  • PSRemoting Domain Controllers 2008 R2

    I am new to powershell and ps remoting but I cannot get remoting to work on my DC's. I followed to same steps on non-DC and they work on the first try. All I am running is this command (Enable-PSRemoting -Force). I have tried turning off the firewall

  • Channel-Group on 5508 Controller

    Ok .. I have an odd question regarding creating channel groups to connect 5508 controllers to my network. Today I have a single 5508 Controller and it is attached to the network using two interfaces configured as a channel group. I am in the process