ThatGuy343
ThatGuy343

Reputation: 2424

Java crop image?

I'm trying to get one section from an image.

From an initial image, how can I return the section 1 below as an image itself?

Instead of the entire 4 squares.

enter image description here

So in short, I wan't to get a 64 x 64 pixel sized rectangle from a base image.

How should I go about this?

Upvotes: 2

Views: 242

Answers (2)

Rahul Tripathi
Rahul Tripathi

Reputation: 172588

You may try like this:

BufferedImage img= ImageIO.read(new File("image.png"));

final int w= 10;
final int h= 10;
final int rows = 5;
final int cols = 5;
BufferedImage[] tile= new BufferedImage[rows * cols];

for (int i = 0; i < rows; i++)
{
    for (int j = 0; j < cols; j++)
    {
        tile[(i * cols) + j] = img.getSubimage(
            j * w,
            i * h,
            w,
            h
        );
    }
}

You may check the getSubimage

Upvotes: 4

Niru
Niru

Reputation: 742

Try this

BufferedImage tile = mImage.getSubimage(x, y, w, h);

where x and y are your starting co-ordinates and w : width and h : height of sub-image.
So to get the 1st square your values will be x=0,y=0,w=64,h=64

Upvotes: 4

Related Questions