How to create transparent pixels in a gif for BufferedImage, then save to a GIF file?

53 Views Asked by At

I have code that creates a simple 5x5 array of java.awt.Color, and then uses that to create a java.awt.image.BufferedImage. The edges of the array are an opaque color (alpha = 255) called o, while the center is a transparent color (alpha = 0) called t.

Finally, I write the image out to file using javax.imageio.ImageIO.write().

Here is the code.

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;

class Irrelevant
{

   public static void main(String[] args) throws Exception
   {
   
      final Color o = new Color(255, 0, 0, 255); //opaque red
      final Color t = new Color(0, 255, 0, 0);   //transparent green -- clear
   
      final Color[][] pixels = //red edges with (ideally) a clear center
         {
            {o, t, t, t, o},
            {o, t, t, t, o},
            {o, t, t, t, o},
            {o, t, t, t, o},
            {o, t, t, t, o}
         };
   
      BufferedImage image = new BufferedImage(pixels.length, pixels[0].length, BufferedImage.TYPE_INT_ARGB);
   
      for (int y = 0; y < pixels.length; y++)
      {
         for (int x = 0; x < pixels[y].length; x++)
         {
            image.setRGB(x, y, pixels[y][x].getRGB());
         }
      }
   
      ImageIO.write(image, "gif", new File("abctest.gif"));
      ImageIO.write(image, "png", new File("abctest.png"));
   
   }

}

However, here is the resulting gif. I am showing it with a purple background to show that the image is NOT transparent in the center, like expected. It is actually black.

Don't mind the fuzziness, that's IrfanView being annoying.

enter image description here

And here is another one in Microsoft Paint. Same gif.

enter image description here

Why are they not clear in the center? And I know I set the alpha correctly because remember, I also saved it as a png as well as a gif. When I save it as a png, it works as expected. Here are screenshots for the png.

enter image description here

enter image description here

Can someone help point me in the right direction?

EDIT - Here is an example image that I did not make.

enter image description here

In IrfanView, it looks like this.

enter image description here

In this gif, the purple shows up correctly, which is what threw me off.

But thanks to the help of @camickr, I am starting to think that it is actually something that only happens on IrfanView because all other image viewers I looked at it through worked. That includes, Photos, Snipping Tool, LibreOffice Draw, and Firefox. All showed a white (or background specific color) when rendering, implying that it is actually transparent.

0

There are 0 best solutions below