NRP : 05111740000068
Kelas : PBO A
pada postingan saya kali ini, saya akan membagikan hasil dari membuat Image Viewer versi 1.0 menggunakan Java. Berikut Source Code serta tampilan GUI.
- Source Code
- ImageViewer
1: import java.awt.*;
2: import java.awt.event.*;
3: import java.awt.image.*;
4: import javax.swing.*;
5: import java.io.File;
6: /**
7: * ImageViewer is the main class of the image viewer application. It builds and
8: * displays the application GUI and initialises all other components.
9: *
10: * To start the application, create an object of this class.
11: *
12: * @author Haikal Almaz Said
13: * @version 26/11/2018
14: */
15: public class ImageViewer
16: {
17: // static fields:
18: private static final String VERSION = "Version 1.0";
19: private static JFileChooser fileChooser = new JFileChooser(System.getProperty("user.dir"));
20: // fields:
21: private JFrame frame;
22: private ImagePanel imagePanel;
23: private JLabel filenameLabel;
24: private JLabel statusLabel;
25: private OFImage currentImage;
26: /**
27: * Create an ImageViewer show it on screen.
28: */
29: public ImageViewer()
30: {
31: currentImage = null;
32: makeFrame();
33: }
34: // ---- implementation of menu functions ----
35: /**
36: * Open function: open a file chooser to select a new image file.
37: */
38: private void openFile()
39: {
40: int returnVal = fileChooser.showOpenDialog(frame);
41: if(returnVal != JFileChooser.APPROVE_OPTION) {
42: return; // cancelled
43: }
44: File selectedFile = fileChooser.getSelectedFile();
45: currentImage = ImageFileManager.loadImage(selectedFile);
46: if(currentImage == null) { // image file was not a valid image
47: JOptionPane.showMessageDialog(frame,
48: "The file was not in a recognized image file format.",
49: "Image Load Error",
50: JOptionPane.ERROR_MESSAGE);
51: return;
52: }
53: imagePanel.setImage(currentImage);
54: showFilename(selectedFile.getPath());
55: showStatus("File loaded.");
56: frame.pack();
57: }
58: /**
59: * Close function: close the current image.
60: */
61: private void close()
62: {
63: currentImage = null;
64: imagePanel.clearImage();
65: showFilename(null);
66: }
67: /**
68: * Quit function: quit the application.
69: */
70: private void quit()
71: {
72: System.exit(0);
73: }
74: /**
75: * 'Darker' function: make the picture darker.
76: */
77: private void makeDarker()
78: {
79: if(currentImage != null) {
80: currentImage.darker();
81: frame.repaint();
82: showStatus("Applied: darker");
83: }
84: else {
85: showStatus("No image loaded.");
86: }
87: }
88: /**
89: * 'Lighter' function: make the picture lighter
90: */
91: private void makeLighter()
92: {
93: if(currentImage != null) {
94: currentImage.lighter();
95: frame.repaint();
96: showStatus("Applied: lighter");
97: }
98: else {
99: showStatus("No image loaded.");
100: }
101: }
102: /**
103: * 'threshold' function: apply the threshold filter
104: */
105: private void threshold()
106: {
107: if(currentImage != null) {
108: currentImage.threshold();
109: frame.repaint();
110: showStatus("Applied: threshold");
111: }
112: else {
113: showStatus("No image loaded.");
114: }
115: }
116: /**
117: * 'Lighter' function: make the picture lighter
118: */
119: private void showAbout()
120: {
121: JOptionPane.showMessageDialog(frame,
122: "ImageViewer\n" + VERSION,
123: "About ImageViewer",
124: JOptionPane.INFORMATION_MESSAGE);
125: }
126: // ---- support methods ----
127: /**
128: * Display a file name on the appropriate label.
129: * @param filename The file name to be displayed.
130: */
131: private void showFilename(String filename)
132: {
133: if(filename == null) {
134: filenameLabel.setText("No file displayed.");
135: }
136: else {
137: filenameLabel.setText("File: " + filename);
138: }
139: }
140: /**
141: * Display a status message in the frame's status bar.
142: * @param text The status message to be displayed.
143: */
144: private void showStatus(String text)
145: {
146: statusLabel.setText(text);
147: }
148: // ---- swing stuff to build the frame and all its components ----
149: /**
150: * Create the Swing frame and its content.
151: */
152: private void makeFrame()
153: {
154: frame = new JFrame("ImageViewer");
155: makeMenuBar(frame);
156: Container contentPane = frame.getContentPane();
157: // Specify the layout manager with nice spacing
158: contentPane.setLayout(new BorderLayout(6, 6));
159: filenameLabel = new JLabel();
160: contentPane.add(filenameLabel, BorderLayout.NORTH);
161: imagePanel = new ImagePanel();
162: contentPane.add(imagePanel, BorderLayout.CENTER);
163: statusLabel = new JLabel(VERSION);
164: contentPane.add(statusLabel, BorderLayout.SOUTH);
165: // building is done - arrange the components and show
166: showFilename(null);
167: frame.pack();
168: Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
169: frame.setLocation(d.width/2 - frame.getWidth()/2, d.height/2 - frame.getHeight()/2);
170: frame.setVisible(true);
171: }
172: /**
173: * Create the main frame's menu bar.
174: * @param frame The frame that the menu bar should be added to.
175: */
176: private void makeMenuBar(JFrame frame)
177: {
178: final int SHORTCUT_MASK =
179: Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
180: JMenuBar menubar = new JMenuBar();
181: frame.setJMenuBar(menubar);
182: JMenu menu;
183: JMenuItem item;
184: // create the File menu
185: menu = new JMenu("File");
186: menubar.add(menu);
187: item = new JMenuItem("Open");
188: item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, SHORTCUT_MASK));
189: item.addActionListener(new ActionListener() {
190: public void actionPerformed(ActionEvent e) { openFile(); }
191: });
192: menu.add(item);
193: item = new JMenuItem("Close");
194: item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, SHORTCUT_MASK));
195: item.addActionListener(new ActionListener() {
196: public void actionPerformed(ActionEvent e) { close(); }
197: });
198: menu.add(item);
199: menu.addSeparator();
200: item = new JMenuItem("Quit");
201: item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, SHORTCUT_MASK));
202: item.addActionListener(new ActionListener() {
203: public void actionPerformed(ActionEvent e) { quit(); }
204: });
205: menu.add(item);
206: // create the Filter menu
207: menu = new JMenu("Filter");
208: menubar.add(menu);
209: item = new JMenuItem("Darker");
210: item.addActionListener(new ActionListener() {
211: public void actionPerformed(ActionEvent e) { makeDarker(); }
212: });
213: menu.add(item);
214: item = new JMenuItem("Lighter");
215: item.addActionListener(new ActionListener() {
216: public void actionPerformed(ActionEvent e) { makeLighter(); }
217: });
218: menu.add(item);
219: item = new JMenuItem("Threshold");
220: item.addActionListener(new ActionListener() {
221: public void actionPerformed(ActionEvent e) { threshold(); }
222: });
223: menu.add(item);
224: // create the Help menu
225: menu = new JMenu("Help");
226: menubar.add(menu);
227: item = new JMenuItem("About ImageViewer...");
228: item.addActionListener(new ActionListener() {
229: public void actionPerformed(ActionEvent e) { showAbout(); }
230: });
231: menu.add(item);
232: }
233: }
- ImagePanel
1: import java.awt.*;
2: import javax.swing.*;
3: import java.awt.image.*;
4: /**
5: * An ImagePanel is a Swing component that can display an OFImage.
6: * It is constructed as a subclass of JComponent with the added functionality
7: * of setting an OFImage that will be displayed on the surface of this
8: * component.
9: *
10: * @author Haikal Almaz Said
11: * @version 26/11/2018
12: */
13: public class ImagePanel extends JComponent
14: {
15: // The current width and height of this panel
16: private int width, height;
17: // An internal image buffer that is used for painting. For
18: // actual display, this image buffer is then copied to screen.
19: private OFImage panelImage;
20: /**
21: * Create a new, empty ImagePanel.
22: */
23: public ImagePanel()
24: {
25: width = 360; // arbitrary size for empty panel
26: height = 240;
27: panelImage = null;
28: }
29: /**
30: * Set the image that this panel should show.
31: *
32: * @param image The image to be displayed.
33: */
34: public void setImage(OFImage image)
35: {
36: if(image != null) {
37: width = image.getWidth();
38: height = image.getHeight();
39: panelImage = image;
40: repaint();
41: }
42: }
43: /**
44: * Clear the image on this panel.
45: */
46: public void clearImage()
47: {
48: Graphics imageGraphics = panelImage.getGraphics();
49: imageGraphics.setColor(Color.LIGHT_GRAY);
50: imageGraphics.fillRect(0, 0, width, height);
51: repaint();
52: }
53: // The following methods are redefinitions of methods
54: // inherited from superclasses.
55: /**
56: * Tell the layout manager how big we would like to be.
57: * (This method gets called by layout managers for placing
58: * the components.)
59: *
60: * @return The preferred dimension for this component.
61: */
62: public Dimension getPreferredSize()
63: {
64: return new Dimension(width, height);
65: }
66: /**
67: * This component needs to be redisplayed. Copy the internal image
68: * to screen. (This method gets called by the Swing screen painter
69: * every time it want this component displayed.)
70: *
71: * @param g The graphics context that can be used to draw on this component.
72: */
73: public void paintComponent(Graphics g)
74: {
75: Dimension size = getSize();
76: g.clearRect(0, 0, size.width, size.height);
77: if(panelImage != null) {
78: g.drawImage(panelImage, 0, 0, null);
79: }
80: }
81: }
- ImageFileManager
1: import java.awt.image.*;
2: import javax.imageio.*;
3: import java.io.*;
4: /**
5: * ImageFileManager is a small utility class with static methods to load
6: * and save images.
7: *
8: * The files on disk can be in JPG or PNG image format. For files written
9: * by this class, the format is determined by the constant IMAGE_FORMAT.
10: *
11: * @author Haikal Almaz Said
12: * @version 26/11/2018
13: */
14: public class ImageFileManager
15: {
16: // A constant for the image format that this writer uses for writing.
17: // Available formats are "jpg" and "png".
18: private static final String IMAGE_FORMAT = "jpg";
19: /**
20: * Read an image file from disk and return it as an image. This method
21: * can read JPG and PNG file formats. In case of any problem (e.g the file
22: * does not exist, is in an undecodable format, or any other read error)
23: * this method returns null.
24: *
25: * @param imageFile The image file to be loaded.
26: * @return The image object or null is it could not be read.
27: */
28: public static OFImage loadImage(File imageFile)
29: {
30: try {
31: BufferedImage image = ImageIO.read(imageFile);
32: if(image == null || (image.getWidth(null) < 0)) {
33: // we could not load the image - probably invalid file format
34: return null;
35: }
36: return new OFImage(image);
37: }
38: catch(IOException exc) {
39: return null;
40: }
41: }
42: /**
43: * Write an image file to disk. The file format is JPG. In case of any
44: * problem the method just silently returns.
45: *
46: * @param image The image to be saved.
47: * @param file The file to save to.
48: */
49: public static void saveImage(OFImage image, File file)
50: {
51: try {
52: ImageIO.write(image, IMAGE_FORMAT, file);
53: }
54: catch(IOException exc) {
55: return;
56: }
57: }
58: }
- OFImage
1: import java.awt.*;
2: import java.awt.image.*;
3: import javax.swing.*;
4: /**
5: * OFImage is a class that defines an image in OF (Objects First) format.
6: *
7: * @author Haikal Almaz Said
8: * @version 26/11/2018
9: */
10: public class OFImage extends BufferedImage
11: {
12: /**
13: * Create an OFImage copied from a BufferedImage.
14: * @param image The image to copy.
15: */
16: public OFImage(BufferedImage image)
17: {
18: super(image.getColorModel(), image.copyData(null),
19: image.isAlphaPremultiplied(), null);
20: }
21: /**
22: * Create an OFImage with specified size and unspecified content.
23: * @param width The width of the image.
24: * @param height The height of the image.
25: */
26: public OFImage(int width, int height)
27: {
28: super(width, height, TYPE_INT_RGB);
29: }
30: /**
31: * Set a given pixel of this image to a specified color. The
32: * color is represented as an (r,g,b) value.
33: * @param x The x position of the pixel.
34: * @param y The y position of the pixel.
35: * @param col The color of the pixel.
36: */
37: public void setPixel(int x, int y, Color col)
38: {
39: int pixel = col.getRGB();
40: setRGB(x, y, pixel);
41: }
42: /**
43: * Get the color value at a specified pixel position.
44: * @param x The x position of the pixel.
45: * @param y The y position of the pixel.
46: * @return The color of the pixel at the given position.
47: */
48: public Color getPixel(int x, int y)
49: {
50: int pixel = getRGB(x, y);
51: return new Color(pixel);
52: }
53: /**
54: * Make this image a bit darker.
55: */
56: public void darker()
57: {
58: int height = getHeight();
59: int width = getWidth();
60: for(int y = 0; y < height; y++) {
61: for(int x = 0; x < width; x++) {
62: setPixel(x, y, getPixel(x, y).darker());
63: }
64: }
65: }
66: /**
67: * Make this image a bit lighter.
68: */
69: public void lighter()
70: {
71: int height = getHeight();
72: int width = getWidth();
73: for(int y = 0; y < height; y++) {
74: for(int x = 0; x < width; x++) {
75: setPixel(x, y, getPixel(x, y).brighter());
76: }
77: }
78: }
79: /**
80: * Perform a three level threshold operation.
81: * That is: repaint the image with only three color values:
82: * white, gray, and black.
83: */
84: public void threshold()
85: {
86: int height = getHeight();
87: int width = getWidth();
88: for(int y = 0; y < height; y++) {
89: for(int x = 0; x < width; x++) {
90: Color pixel = getPixel(x, y);
91: int brightness = (pixel.getRed() + pixel.getBlue() + pixel.getGreen()) / 3;
92: if(brightness <= 85) {
93: setPixel(x, y, Color.BLACK);
94: }
95: else if(brightness <= 170) {
96: setPixel(x, y, Color.GRAY);
97: }
98: else {
99: setPixel(x, y, Color.WHITE);
100: }
101: }
102: }
103: }
104: }
No comments:
Post a Comment