BufferedImage仅显示为黑色

时间:2014-12-26 18:03:35

标签: java image bufferedimage imageicon

我正在尝试编写纸牌游戏。我有像系统一样的精灵表来获得个人卡片。这是我的Deck类的代码(没有一些函数):

    private final int ROWS=5;
    private final int COLS=13;
    private ImageIcon [][] picts =new ImageIcon[ROWS][COLS];
    static private BufferedImage bimg;

    public Deck(){

        ImageIcon ic = new ImageIcon(getClass().getResource("/pic/cards.png"));
        int imageHeight = ic.getIconHeight();
        int imageWidth  = ic.getIconWidth();

        bimg = new BufferedImage(imageWidth ,imageHeight, BufferedImage.TYPE_INT_RGB);

        int px=0, py=0, w=imageWidth/COLS, h=imageHeight/ROWS;
        System.out.println("width:"+w+" hieght:"+h);
        for(int i=0;i<ROWS;i++){
            px=0;
            for(int j=0;j<COLS;j++){
                picts[i][j]=new ImageIcon(bimg.getSubimage(px, py, w, h));
                px+=w;
            }
            py+=h;
        }
    }

当我在自己的JPanel类上绘制单个ImageIcons或大BufferedImage时,一切都只是黑色。当我尝试将TYPE_INT_RGB更改为ARGB时,图像变得完全透明且无大小。这也发生在jpg版本的图像上。 我试过g.drawImage(...,frame); g.drawImage(...,this); g.drawImage(...,null);但它不会影响显示。 同样重要的是要注意我有一个背景图像,显示正常:

    public void paintComponent(Graphics g){
        super.paintComponent(g);
        g.drawImage(bg, 0, 0, null);//works
        g.drawImage(cards.getOP(), 30, 30, frame);//does not
    }

我读过其他似乎没有帮助的帖子,例如: BufferedImage produces black output BufferedImage not displaying (all black) but Image can be displayed

1 个答案:

答案 0 :(得分:1)

  

,一切都只是黑色。

bimg = new BufferedImage(imageWidth ,imageHeight, BufferedImage.TYPE_INT_RGB);

那是因为您所做的就是创建一个空白的BufferedImage。获取umnpainted图像的子图像会为您提供未上漆的图像。

使用ImageIO将图像直接读入BufferedImage:

bimg = ImageIO.read(...);

现在你应该可以获得你的subImage。