Java BufferedImage: Beware of getSubimage!

| No Comments
Wow, I just spent way too long trying to figure out a bug in some of my gaming code. Nothing made sense no matter how many times I looked at the problem and how many angles I considered. The weirdest things were happening in my graphical output, and I was getting very frustrated.

I got desperate and decided to look over the APIs of all the graphical functions I was using. Then I looked at the BufferedImage.getSubimage function API and it was painfully obvious:

getSubimage

public BufferedImage getSubimage(int x,
                                 int y,
                                 int w,
                                 int h)

    Returns a subimage defined by a specified rectangular region. The returned BufferedImage shares the same data array as the original image.

    Parameters:
        w - the width of the specified rectangular region
        h - the height of the specified rectangular region
    Returns:
        a BufferedImage that is the subimage of this BufferedImage.
    Throws:
        RasterFormatException - if the specified area is not contained within this BufferedImage.

I had assumed that getSubimage would return a new BufferImage array, but it actually is really just a map to part of the original BufferImage array. Consequently, whenever I was painting in the new BufferImage object, I was actually painting all over my original BufferImage!

Well, that was a lesson learned the really hard way.

Leave a comment

The site blog for indicium.us.
Linux Projects
Online Games
Unsung Linux Games

RSS Feed

Powered by Movable Type 4.21-en
and GNU/Linux


Creative Commons License
The content of this blog is licensed under a Creative Commons Attribution-Share Alike 3.0 United States License. See my copyleft page for more details.