gpt4 book ai didi

java - 为什么 java.awt.image.BufferedImage#getType 会返回不同的值 Mac & CENTOS

转载 作者:行者123 更新时间:2023-11-30 09:52:02 25 4
gpt4 key购买 nike

我对 BufferedImage#getType 有疑问方法。当从文件系统引用 PNG 图像时,以下代码将在我的 Mac 中打印 5 并在 CENTOS 框中使用此 JVM 打印 0:

Java 版本“1.6.0_03”Java(TM) SE 运行时环境(build 1.6.0_03-b05)Java HotSpot(TM) 64 位服务器 VM(内部版本 1.6.0_03-b05,混合模式)

import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.*;

public class ImageTypeTest {

public static void main(String[] args) throws Exception{
BufferedImage sourceImage = ImageIO.read(new File("/path/to/png.png"));
System.out.println(sourceImage.getType());
}

}

任何人都可以阐明可能导致这种差异的原因,以便我可以解决它吗?该代码为其他图像类型(例如 GIF 图像)返回相同的值。

谢谢

最佳答案

差异的原因是 OS X 和 CENTOS 中的 Java 实现使用不同的底层库来解析 PNG 图像——它们被允许这样做,因为 ImageIO 的契约(Contract)中没有任何内容要求它生成特定的图像类型.

如果你想有一个一致的(和快速绘制)图像,最好的办法是使用下面的代码将图像转换成显示系统正在使用的颜色空间:

GraphicsConfiguration config = new JFrame().getGraphicsConfiguration();
// Or better, use your main GUI component instead of new JFrame()
BufferedImage fixedImg = config.createCompatibleImage(img.getWidth(), img.getHeight(), Transparency.TRANSLUCENT);
Graphics2D fig = fixedImg.createGraphics();
fig.drawImage(img, 0, 0, null);
fig.dispose();
fixedImg.flush();

关于java - 为什么 java.awt.image.BufferedImage#getType 会返回不同的值 Mac & CENTOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4391814/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com