Search code examples
javaimagegraphicsgraphics2dimage-clipping

How do I copy part of one image to another?


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.


Solution

  • First, some notes regarding Andreas_D answer below:

    • His code relies on sun.java2d.SunGraphics2D which is an internal and undocumented OpenJDK class. This means that, while it might compile and run on your computer, it might will probably break if you distribute the code to other people. For a detailed discussion, see the official statement regarding this.

    • The code relies on reflection to pry the internal class open which is a code smell in it self.

    • All in all, his approach is an example of exceptionally bad practice (both when it comes to programming style and when it comes to helping fellow programmers to use the API correctly)


    how do I get that img from the sourceGraphics2D?

    I suspect you misunderstood the responsibility of the Graphics2D class.

    You use the Graphics2D class to draw on something. It is capable of drawing on a BufferedImage (if you got the graphics object from a buffered image), the screen (if you got it as an argument to your paintComponent method) or even a printer. So in other words, given a Graphics2D objects, there might not even exist an image!

    So, as you probably understand, the Graphics2D API does not provide methods for getting hold of the underlying image. (Such method wouldn't make sense, the graphics object might be passing on lines and text being drawn to a printer!)

    To get hold of a subimage you need to get hold of the underlying image which the given graphics object draws upon.