How do I copy part of one image to another?

Joshua Fox picture Joshua Fox · Dec 6, 2010 · Viewed 12.4k times · Source

I want to copy part of one image into another smaller one: in other words, copy a subrectangle.

I have a Graphics2D object for the source, I can make one for the target, and I know about targetGraphics2D.drawImage(Image img,....) , but how do I get that img from the sourceGraphics2D?


Answer (per aioobe): The source needs to be an Image rather than a Graphics2D.

Image.subImage() is the method for getting the relevant part of the source.

Answer

Tansir1 picture Tansir1 · Dec 6, 2010

As Aioobe said, you're not going to get the image from the Graphics2D alone. But if your sourceGraphics2D is coming from a Swing component you could try invoking its paint methods with your own Graphics2D instance. From there you can copy the interesting sub-region.

This is kind of a hack but it should work assuming you're using Swing objects.

class CopySwingPaintingSubRegion extends TheSourceType
{
       private BufferedImage bufImg;

       public CopySwingPaintingSubRegion()
       {
          bufImg = new BufferedImage(...);

          //Draw the original image into our bufImg for copying
          super.paintComponent(bufImg.createGraphics());
       }

       public BufferedImage getSubImage(int x, int y, int w, int h)
       {
          return bufImg.getSubImage(x,y,w,h);
       }
}