各位大虾,请教一个问题:我想获得指定图片的RGB数组,代码如下:
ImageIcon   icon   =   new   ImageIcon("c:\\copy.jpg");  
int   imgHeight   =   icon.getIconWidth();  
int   imgWidth   =   icon.getIconHeight(); 
int[] data = new int[imgHeight*imgWidth];
BufferedImage image = new BufferedImage(imgWidth,imgHeight,BufferedImage.TYPE_INT_ARGB);
Graphics2D   g2d = image.createGraphics();  
g2d.drawImage(icon.getImage(),0,0,icon.getImageObserver()); 
image.getRGB(0, 0, imgWidth, imgHeight, data, 0, imgWidth);
现在关键是最后一句,我通过image.getRGB来获得RGB数组,可为何该数组里面的值都是-1,没有读到?
请各位大虾帮小弟一把。而且图片确实存在,此图像的高和宽都可获得,就是RGB数组显示出来的全是-1. 谢谢!

解决方案 »

  1.   

    icon.getImage()得到的Image是使用异步加载的方式,你可以在取得Image之后调用下面的方法让Image完全加载完再取像素,或者直接使用ImageIO.read()将图片读取到BufferedImage    public static void waitImage(Component c, Image im) {
            MediaTracker mt = new MediaTracker(c);
            mt.addImage(im, 0);
            try {
                mt.waitForID(0);
            } catch (Exception e) {
                e.printStackTrace();
            }
            mt = null;
        }