52 g.drawImage(bi, dx, dy, dx + cw, dy + ch, sx, sy, sx + cw, sy + ch, null);
53 }
54 }
55 }
56 public static void main(String[] args) {
57 JFrame frame = new JFrame();
58 frame.setTitle("BufferedImage");
59 frame.setSize(1000, 600);
60 frame.addWindowListener(new WindowAdapter() {
61 public void windowClosing(WindowEvent e) {
62 System.exit(0);
63 }
64 });
65 Container contentPane = frame.getContentPane();
66 MyTest p = new MyTest();
67 contentPane.add(p);
68 p.doExchange();
69 frame.show();
70 }
71 }
2) 通过多种方式在(利用Graphics2D.drawImage()的不同重载方法)目标Graphics上绘制多种处理后的图像,如缩放、ConvolveOp的锐化,RescaleOp的改变亮度等。
1 public class MyTest extends JPanel {
2 private BufferedImage bi;
3 private static int ALL_WIDTH = 900;
4 private static int ALL_HEIGHT = 600;
5 private int w, h;
6 public static final float[] SHARPEN3x3 = { 0.f, -1.f, 0.f, -1.f, 5.f, -1.f, 0.f, -1.f, 0.f };
7 //可以将1,1坐标的锐化data替换为这里的模糊data,该观察效果。
8 public static final float[] BLUR3x3 = { 0.1f, 0.1f, 0.1f, 0.1f, 0.2f, 0.1f, 0.1f, 0.1f, 0.1f };
9 public MyTest() {
10 try {
11 // 这里的样例图片是截取的桌面背景,width和height都是比较大的,
12 // 同时为了简化代码突出重点,因此这里只是给出了固定的宽和高
13 bi = ImageIO.read(new File("D:/desktop.png"));
14 // 由于我们的整个JFrame将同时显示六种(2行*3列)不同效果的目标
15 // 子图像,因此这里需要针对原图的宽和高作特殊处理,并取出子图像
16 bi = bi.getSubimage(0, 0, ALL_WIDTH / 3, ALL_HEIGHT / 2);
17 w = bi.getWidth();
18 h = bi.getHeight();
19 if (bi.getType() != BufferedImage.TYPE_INT_RGB) {
20 BufferedImage bi2 = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
21 bi2.getGraphics().drawImage(bi, 0, 0, null);
22 bi = bi2;
23 }
24 } catch (IOException e) {
25 }
26 }
27 public void paintComponent(Graphics g) {
28 super.paintComponent(g);
29 Graphics2D g2 = (Graphics2D) g;
30
31 int offsetx = 0;
32 int offsety = 0;
33 // 1. 在0,0的位置显示原始图像
34 g.drawImage(bi, offsetx, offsety, null);
35 offsetx += bi.getWidth();
36 // 2. 在0,1的位置显示通过原始坐标进行缩放的图像,该行代码将原始图像的部分图像放大一倍
37 g.drawImage(bi, offsetx, offsety, offsetx + w, offsety + h, 0, 0, w / 2, h / 2, null);
38 offsetx += bi.getWidth();
39 // 3. 在0,2的位置显示通过AffineTransform进行缩放后的图像
40 AffineTransform at = AffineTransform.getTranslateInstance(offsetx, offsety);
41 at.scale(0.7, 0.7);
42 g2.drawImage(bi, at, null);
43 offsetx = 0;
44 offsety += bi.getHeight();
45 // 4. 在1,0的位置显示通过AffineTransformOp处理后的图像.
46 // AffineTransformOp是通过TYPE_BICUBIC(质量最高的)提示将原始图像进行缩放。
47 AffineTransform at2 = AffineTransform.getScaleInstance(1.5, 1.5);
48