Search code examples
javaarraysgraphicsscalepixel

Scaling a Pixel Array in Java


I have been messing around with re-sizing arrays of pixels. I have managed to make some code that scales up the pixels when they are rendered. The problem with the code is that I can only scale the pixels up with whole numbers (1, 2, 3, etc.). I want to be able to scale the pixels up using a double (.001, .002, etc) so I am not restrained to only a few image sizes. Here is the code I wrote:

public void draw(Sprite s, int xCord, int yCord, int scale){
    for(int y = 0; y < s.getHeight()*scale; y++){
        for(int x = 0; x <s.getWidth()*scale; x++){
            pixels[(x+xCord) +(y+yCord)*this.width]
                = s.pixels[(x/scale+ y/scale * s.getWidth())];
        }       
    }
}

Can this be easily tweaked to allow for non-whole number scales?

The class Sprite knows its own width and height given by s.getWidth() and s.getHeight(). The height and width are the actual dimensions in pixels of the .png when it was read.


Solution

  • For flexibility in choosing the resampling algorithm, use AffineTransformOp, as shown here, or just let the graphics context handle it, as shown here.