본문 바로가기

Java프로그래밍

이미지 로딩 및 디스플레이

반응형
이미지를 읽어들여서 화면에 표시하는 소스코드입니다.
BufferedImage 클래스와 WritableRaster 클래스를 이용합니다.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package univ.inu.embedded.imgeditor;

import java.awt.*;
import java.awt.image.*;
import java.io.*;

import javax.imageio.*;
import javax.swing.*;

public class ImageFrame extends JFrame {

	private int width = 0;
	private int height = 0;
	private BufferedImage img = null;
	private MyImgPanel imgPanel = null;
	
	private class MyImgPanel extends JComponent
	{
		
		public void paint(Graphics g)
		{
			Graphics2D g2 = (Graphics2D)g;
			g2.drawImage(img, 0, 0, null);
		}
	}
	
	private void loadImage(String fname)
	{
		try {
			img = ImageIO.read(new File(fname));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		WritableRaster wr = img.getRaster();
		
		int[] pixelValue = new int[3];
		
		for (int i = 0; i < img.getWidth(); i++)
		{
			for (int j = 0; j < img.getHeight(); j++)
			{
				wr.getPixel(i, j, pixelValue);
				int v = (pixelValue[0]+pixelValue[1]+pixelValue[2])/3;
				
				if (v > 127)
				{
					v = 255;
				}
				else
				{
					v = 0;
				}
				
				pixelValue[0] = v;
				pixelValue[1] = v;
				pixelValue[2] = v;
				wr.setPixel(i, j, pixelValue);
			}
		}

	}
	
	public ImageFrame ()
	{
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		loadImage("dog.jpg");
		width = img.getWidth();
		height = img.getHeight();
		
		imgPanel = new MyImgPanel();
		imgPanel.setSize(width, height);
		
		this.add(imgPanel);
		this.setSize(width+10, height+10);
		this.setVisible(true);
		
	}
	
	public static void main(String argv[])
	{
		new ImageFrame();
	}

}


반응형