halfway258
halfway258

Reputation: 175

BufferedImage displaying as only black

I'm trying to code a card game. I have a sprite sheet like system to get individual cards. This is the code for my Deck class (without some functions):

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

When I paint the individual ImageIcons or the big BufferedImage on my own JPanel class, everything is just black. When I try to change TYPE_INT_RGB to ARGB the image turns completely transparent and sizeless. This also happens with a jpg version of the image. I tried g.drawImage(..., frame);g.drawImage(..., this);g.drawImage(..., null); but it doesn't affect the display. Also important to note that I have a background Image that does display fine:

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

I read other posts that didn't seem to help such as: BufferedImage produces black output BufferedImage not displaying (all black) but Image can be displayed

Upvotes: 0

Views: 2022

Answers (1)

camickr
camickr

Reputation: 324088

, everything is just black.

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

That's because all you do is create a blank BufferedImage. Getting a subImage of an umnpainted image gives you an unpainted image.

Use ImageIO to read the image directly into a BufferedImage:

bimg = ImageIO.read(...);

Now you should be able to get your subImage.

Upvotes: 1

Related Questions