4

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/and 或 Java Bug 有什么问题

4

2 回答 2

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

因此,您实施的最后一部分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);
于 2011-01-05T22:33:10.897 回答
0

试试这个:

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

这使它工作。当然,问题是为什么..?

于 2011-01-05T18:32:10.867 回答