Solved

Create transparent GIF with JAI

Posted on 2006-12-01
14
2,407 Views
Last Modified: 2008-01-09
Hello,
I'm trying to create a transparent GIF with JAI:

  private static void createImage(BufferedImage argBufferedImage, String argFileName) {
    ImageWriter gifWriter = null;
    IIOImage iioImage = null;
    IIOMetadata iioMetadata = null;

    IIOMetadataNode gifMetadataNode = null;
    IIOMetadataNode tmpNode = null;

    gifWriter = (ImageWriter) ImageIO.getImageWritersByFormatName("gif").next();
    try {
      gifWriter.setOutput(ImageIO.createImageOutputStream(new File(argFileName)));
      iioMetadata = gifWriter.getDefaultImageMetadata(new ImageTypeSpecifier(argBufferedImage), null);
      gifMetadataNode = (IIOMetadataNode) iioMetadata.getAsTree("javax_imageio_gif_image_1.0");
      tmpNode = (IIOMetadataNode) gifMetadataNode.getElementsByTagName("GraphicControlExtension").item(0);
      tmpNode.setAttribute("transparentColorIndex", "0");
      tmpNode.setAttribute("transparentColorFlag", "true");
      iioMetadata.setFromTree("javax_imageio_gif_image_1.0", gifMetadataNode);
      iioImage = new IIOImage(argBufferedImage, null, iioMetadata);
      gifWriter.write(iioImage);
      gifWriter.dispose();
    } catch (Exception e) {
      System.out.println("ex:" + e);
    }
  }

Unfortunately my code doesn't work. Any recommendations?
0
Comment
Question by:egono
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
14 Comments
 
LVL 24

Expert Comment

by:sciuriware
ID: 18055718
Any error messages?

;JOOP!
0
 
LVL 2

Author Comment

by:egono
ID: 18055801
No - the background color is just not set transparent.

I get a

java.lang.NullPointerException
      at com.sun.media.imageioimpl.common.PaletteBuilder.findPaletteEntry(PaletteBuilder.java:349)
      at com.sun.media.imageioimpl.common.PaletteBuilder.getIndexColorModel(PaletteBuilder.java:335)
      at com.sun.media.imageioimpl.common.PaletteBuilder.getIndexedImage(PaletteBuilder.java:184)
      at com.sun.media.imageioimpl.common.PaletteBuilder.createIndexedImage(PaletteBuilder.java:116)
      at com.sun.media.imageioimpl.plugins.gif.GIFImageWriter.write(GIFImageWriter.java:602)
      at com.sun.media.imageioimpl.plugins.gif.GIFImageWriter.write(GIFImageWriter.java:530)
      at javax.imageio.ImageWriter.write(ImageWriter.java:573)

if I want to create a complete transparent gif. But this seems to be a known bug: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6287936
Again - the NPE is *not* my problem.

regards
0
 
LVL 35

Expert Comment

by:girionis
ID: 18060171
Can you try to upgrade/downgrade the library?
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 2

Author Comment

by:egono
ID: 18067046
girionis - I could try this, but the environment is given because the jai libs are used for other things too.

the question is: is my code the right way to create a transparent gif?
0
 
LVL 35

Expert Comment

by:girionis
ID: 18067127
Not sure tbh. But the exception you get means that something is not loaded up properly so I guess there is a problem either with some sort fo configuration or with the package itself.
0
 
LVL 2

Author Comment

by:egono
ID: 18067178
girionis - no the exception is a know bug for complete transparent images, and again this is not my problem.

maybe I should change my question into: How to create a transparent gif with JAI?
0
 
LVL 35

Expert Comment

by:girionis
ID: 18067210
This link: http://www.esri.com/software/arcexplorer/about/ae9_faq.html states that this is a limitation. Maybe you can create a transparent PNG and then convert it to GIF?
0
 
LVL 2

Author Comment

by:egono
ID: 18067234
some more info. here is how I create my BufferedImage:

        bufferedImage = new BufferedImage(argWidth, argHeight, BufferedImage.TYPE_INT_ARGB);

        graphics2D = bufferedImage.createGraphics();
        if (colorIdx == 0) {
          graphics2D.setBackground(Color.WHITE);
        } else {
          graphics2D.setBackground(Color.BLACK);
        }
        graphics2D.clearRect(0, 0, argWidth, argHeight);
        graphics2D.setColor(Color.BLUE);
        graphics2D.fillRect(0, 0, 10, 10);
0
 
LVL 2

Author Comment

by:egono
ID: 18067256
girionis - I'm not displaying the gif with jai, I just want to save it (I'm using Paint.Net to view it)
0
 
LVL 35

Expert Comment

by:girionis
ID: 18067369
If you just want to save it just use one of the usual output stream methods that write the binary data on the disk. But I guess the problem is that the image is not what you want and therefore before you save it you need it to be transparent. Not sure how exactly you can do it, but from a quick search on jai-interest archives I found the following URL for GIF files: http://archives.java.sun.com/cgi-bin/wa?A2=ind9902&L=jai-interest&P=R5968&I=-3

You might also want to try this: http://archives.java.sun.com/cgi-bin/wa?S1=jai-interest and do a search for "GIF encoding".
0
 
LVL 2

Author Comment

by:egono
ID: 18174435
Now here is a working solution. The trick is to use a IndexColorModel for the image. The createColorModel() method should create the desired color model, in my case a model with just 2 colors (first one is black).

create the image with

[...]
          bufferedImage = new BufferedImage(argWidth, argHeight, BufferedImage.TYPE_BYTE_INDEXED,                                             createColorModel(COLORS[colorIdx]));
[...]


private static IndexColorModel createColorModel(Color argColor) {
    IndexColorModel result = null;
    result = new IndexColorModel(1, 2,
                                 new byte[] {0, (byte)argColor.getRed()},
                                 new byte[] {0, (byte)argColor.getGreen()},
                                 new byte[] {0, (byte)argColor.getBlue()},
                                 0);
    return result;
 }

  private static void createImage(BufferedImage argBufferedImage, String argFileName) {
    ImageWriter gifWriter = null;
    IIOImage iioImage = null;
    IIOMetadata iioMetadata = null;
    gifWriter = (ImageWriter) ImageIO.getImageWritersByFormatName("gif").next();
    try {
      gifWriter.setOutput(ImageIO.createImageOutputStream(new File(argFileName)));
      iioMetadata = gifWriter.getDefaultImageMetadata(new ImageTypeSpecifier(argBufferedImage), null);
      iioImage = new IIOImage(argBufferedImage, null, iioMetadata);
      gifWriter.write(iioImage);
    } catch (Exception e) {
      System.out.println("ex:" + e);
    }

  }


that's it :-)
0
 
LVL 35

Expert Comment

by:girionis
ID: 18185742
Fine by me.
0
 
LVL 1

Accepted Solution

by:
DarthMod earned 0 total points
ID: 18221518
PAQd, 500 points refunded.

DarthMod
CS Moderator
0

Featured Post

Creating Instructional Tutorials  

For Any Use & On Any Platform

Contextual Guidance at the moment of need helps your employees/users adopt software o& achieve even the most complex tasks instantly. Boost knowledge retention, software adoption & employee engagement with easy solution.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
swing controls 2 38
web project error add remove 1 84
Java Inheritance super keyword use 8 73
Which is best Image Resizing Web service 11 42
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
The viewer will learn how to implement Singleton Design Pattern in Java.

751 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question