public class Graphics2DExample extends JFrame
1: import javax.swing.JFrame;
2: import java.awt.Graphics;
3: import java.awt.Graphics2D;
4: import java.awt.image.BufferedImage;
5: import java.awt.image.RescaleOp;
6: import javax.imageio.ImageIO;
7: import java.io.File;
8: import java.io.IOException;
9:
10: public class Graphics2DExample extends JFrame
11: {
12: public void paint(Graphics canvas)
13: {
14: super.paint(canvas);
15: try
16: {
17: // Load image from default location on disk. This is inefficient
18: // because the image will be re-loaded everytime the JFrame is
19: // displayed. A better technique would be to load the image
20: // once in the constructor (discussed in a later chapter).
21: BufferedImage img = ImageIO.read(new File("java.jpg"));
22: // Draw the image at coordinate 50,50
23: canvas.drawImage(img, 50, 50, null);
24:
25: // Copy the image to another buffer with a
26: // color model (ARGB) to support alpha blending
27: // that allows translucency
28: int w = img.getWidth(null);
29: int h = img.getHeight(null);
30: BufferedImage img2 = new
31: BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
32: Graphics g = img2.getGraphics();
33: g.drawImage(img, 0, 0, null);
34:
35:
36: // Create a rescale filter operation that
37: // makes the image 30% opaque
38: float[] scales = { 1f, 1f, 1f, 0.3f };
39: float[] offsets = new float[4];
40: RescaleOp rop = new RescaleOp(scales, offsets, null);
41: // Draw the image, applying the filter
42: Graphics2D g2 = (Graphics2D) canvas;
43: g2.drawImage(img2, rop, 150, 50);
44: }
45: catch (IOException e)
46: {
47: System.out.println("Error reading the image.");
48: }
49: }
50: public Graphics2DExample()
51: {
52: setSize(275,175);
53: setDefaultCloseOperation(EXIT_ON_CLOSE);
54: }
55: public static void main(String[] args)
56: {
57: Graphics2DExample guiWindow = new Graphics2DExample();
58: guiWindow.setVisible(true);
59: }
60: }