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有什么问题
最佳答案 以下是通过ImageIO加载时链接图像的ColorModel的字符串表示形式:
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中编码).
你可以通过以下方式解决它:
>使用全白像素初始化BufferedImage
>使用AlphaComposite.SrcOver
因此,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);