9.4. Drawing on Images
Up until now, I've treated an image as something that gets rendered on a drawing surface. But the image itself can be a drawing surface. The Image class provides the following method for this purpose:
public abstract Graphics getGraphics()
This method returns a Graphics instance that renders to this Image. This method is supported only for application-created offscreen images. In particular, images that represent external image data, like those returned from the getImage() methods in Applet and Toolkit, will throw an Illegal-AccessError from this method.
BufferedImage , as a subclass of Image, also has a getGraphics() method. However, it is deprecated. You should use the createGraphics() method instead, as it explicitly returns a Graphics2D instead of a Graphics:
public Graphics2D createGraphics()
Use this method to obtain a Graphics2D that represents this BufferedImage as a drawing surface.
The following example shows the two-faced nature of Images. It creates an image, draws on it, and then renders the modified image to the screen. It demonstrates that an image can be rendered on a drawing surface as well as being a drawing surface itself.
import java.awt.*; import java.awt.event.*; import java.awt.image.*; import java.io.*; import com.sun.image.codec.jpeg.*; public class ImageDuplicity extends Component { public static void main(String[] args) { ApplicationFrame f = new ApplicationFrame("ImageDuplicity v1.0"); f.setLayout(new BorderLayout()); Component ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access