为什么在使用Java ImageIO调整大小时,此GIF最终会变为黑色方块

时间:2011-01-05 17:26:02

标签: java resize gif javax.imageio

Java ImageIO正确地显示了这个黑色&白色图片http://www.jthink.net/jaikoz/scratch/black.gif但是当我尝试使用此代码调整大小时

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;
}

我最后得到一张黑色图片。我试图让图像更小(缩略图),但即使我为了测试目的而调整它的大小,它仍然最终成为黑色方块。

其他图片调整大小没问题,任何人都知道gif /和/或Java Bug有什么问题

2 个答案:

答案 0 :(得分:2)

以下是通过ColorModel加载时链接图片ImageIO的字符串表示形式:

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

如果我理解正确,每个像素有一位,其中0位是不透明的黑色,1位是透明的。您的BufferedImage最初都是黑色的,因此在其上绘制黑色和透明像素的混合将无效。

虽然您正在使用AlphaComposite.Src,但这不会有帮助,因为透明调色板条目的R / G / B值读为零(我不确定这是在GIF中编码还是仅在JDK。)

您可以通过以下方式解决问题:

  1. 使用全白像素初始化BufferedImage
  2. 使用AlphaComposite.SrcOver
  3. 所以resize2D实施的最后一部分将成为:

    // 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);
    

答案 1 :(得分:0)

试试这个:

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

这使它成功。当然,问题是为什么......?