Search code examples
javacopybufferedimageraster

Copy specific part of a bufferimage into another bufferimage


I have one big buffer image.

I want to create another buffer image with the data from the first one

I tried making a raster with buffer.getData(new Rectangle(x,y,width,height))

And then buffer2.setData(raster)

But from reason the data is translated by x,y instead of being 0,0.For example if I have a pixel at x,y in the original I will still have it at x,y in the new one instead of 0,0 because the x,y is where the rectangle is translated.

So is there a way to translate the raster properly OR is there a better solution to copying the image?

Edit: I also managed to do it with getGraphics().drawImage(). There is a method for defining 2 rectangles by defining their corners. But the method below is better because it does not overdraw.

Edit2: Seems like the subimage is connected to the original,is there another way to create a bufferimage with the cut data and dimensions that are actually original?


Solution

  • Java sub image should work for you.. try;

    imageTwo = imageOne.getSubimage(x, y, width, height);
    

    Hope it helps :-)