Why does this GIF end with a black square when resizing using Java ImageIO

Java ImageIO correctly displays this black and white image http://www.jthink.net/jaikoz/scratch/black.gif , but when I try to change it using this code

public static BufferedImage resize2D(Image srcImage, int size) { int w = srcImage.getWidth(null); int h = srcImage.getHeight(null); // Determine the scaling required to get desired result. float scaleW = (float) size / (float) w; float scaleH = (float) size / (float) h; MainWindow.logger.finest("Image Resizing to size:" + size + " w:" + w + ":h:" + h + ":scaleW:" + scaleW + ":scaleH" + scaleH); //Create an image buffer in which to paint on, create as an opaque Rgb type image, it doesn't matter what type //the original image is we want to convert to the best type for displaying on screen regardless BufferedImage bi = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB); // Set the scale. AffineTransform tx = new AffineTransform(); tx.scale(scaleW, scaleH); // Paint image. Graphics2D g2d = bi.createGraphics(); g2d.setComposite(AlphaComposite.Src); g2d.drawImage(srcImage, tx, null); g2d.dispose(); return bi; } 

I just get a black image. I'm trying to make the picture smaller (thumbnail), but even if I resize it for testing purposes, it will still turn out to be a black square.

Other images change in order, does anyone know what the problem is with gif / and / or Java error

+4
source share
2 answers

Here is a string representation of the ColorModel linked image when loading through ImageIO :

 IndexColorModel: #pixelBits = 1 numComponents = 4 color space = java.awt.color.ICC_ColorSpace@1572e449 transparency = 2 transIndex = 1 has alpha = true isAlphaPre = false 

If I understand this correctly, you have one bit per pixel, where bit 0 opaque and bit 1 is transparent. Your BufferedImage initially all black, so applying a mixture of black and transparent pixels to it will have no effect.

Although you use AlphaComposite.Src , this will not help, since the R / G / B values ​​for writing a transparent palette are considered to be zero (I'm not sure if this is encoded in GIF or just by default in JDK.)

You can get around this:

  • Initializing a BufferedImage with All White Pixels
  • Using AlphaComposite.SrcOver

So, the last part of your resize2D implementation will look like this:

 // Paint image. Graphics2D g2d = bi.createGraphics(); g2d.setColor(Color.WHITE); g2d.fillRect(0, 0, size, size); g2d.setComposite(AlphaComposite.SrcOver); g2d.drawImage(srcImage, tx, null); 
+2
source

Try the following:

 BufferedImage bi = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB); 

It makes it work. Of course, the question is why ..?

0
source

Source: https://habr.com/ru/post/1334397/


All Articles