开发者

Why would java.awt.image.BufferedImage#getType return different value Mac & CENTOS

I have a question about the BufferedImage#getType method. When referencing a PNG image from the file system, the following code will print 5 in my Mac and 0 in a CENTOS box with this JVM:

java version "1.6.0_03" Java(TM) SE Runtime Environment (build 1.6.0_03-b05) Java HotSpot(TM) 64-Bit Server VM (build 1.6.0_03-b05, mixed mode)

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

}

Can anyone please shed some light as to what might be causing this difference so that I can work around it? The code returns the same values for other image types, say GIF images.

Thank you


The reason for the difference is that the Java implementations in OS X and CENTOS use different underlying libraries to parse the PNG image - which they're allowed to, as there is nothing in ImageIO's contract requiring it to produce a particular image type.

If you want to have a consistent (and fast to draw) image, the best thing to do is to use the following code to convert the image into the colour space being used by the display system:

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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜