EAS PBO-B

Berikut merupakan ImageViewer yang saya kembangkan dari ImageViewer 3.0 sebelumnya dengan penambahan fitur crop.




1. Image Viewer
1:  import java.awt.*;  
2:  import java.awt.event.*;  
3:  import javax.swing.*;  
4:  import javax.swing.border.*;  
5:  import java.io.File;  
6:  import java.util.List;  
7:  import java.util.ArrayList;  
8:  /**  
9:   * ImageViewer is the main class of the image viewer application. It builds and  
10:   * displays the application GUI and initialises all other components.  
11:   *   
12:   * To start the application, create an object of this class.  
13:   *   
14:   * @author Michael Kolling and David J Barnes   
15:   * @version 3.0  
16:   */  
17:  public class ImageViewer  
18:  {  
19:    // static fields:  
20:    private static final String VERSION = "Version 3.0";  
21:    private static JFileChooser fileChooser = new JFileChooser(System.getProperty("user.dir"));  
22:    // fields:  
23:    private JFrame frame;  
24:    private ImagePanel imagePanel;  
25:    private JLabel filenameLabel;  
26:    private JLabel statusLabel;  
27:    private JButton smallerButton;  
28:    private JButton largerButton;  
29:    private JToggleButton cropButton;  
30:    private OFImage currentImage;  
31:    private CropEvent cropEvent;  
32:    private List<Filter> filters;  
33:    /**  
34:     * Create an ImageViewer and display its GUI on screen.  
35:     */  
36:    public ImageViewer()  
37:    {  
38:      currentImage = null;  
39:      filters = createFilters();  
40:      makeFrame();  
41:    }  
42:    public static void main(String[] args) {  
43:      new ImageViewer();  
44:    }  
45:    // ---- implementation of menu functions ----  
46:    /**  
47:     * Open function: open a file chooser to select a new image file,  
48:     * and then display the chosen image.  
49:     */  
50:    private void openFile()  
51:    {  
52:      int returnVal = fileChooser.showOpenDialog(frame);   
53:      if(returnVal != JFileChooser.APPROVE_OPTION) {  
54:        return; // cancelled  
55:      }  
56:      File selectedFile = fileChooser.getSelectedFile();  
57:      currentImage = ImageFileManager.loadImage(selectedFile);  
58:      if(currentImage == null) {  // image file was not a valid image  
59:        JOptionPane.showMessageDialog(frame,  
60:            "The file was not in a recognized image file format.",  
61:            "Image Load Error",  
62:            JOptionPane.ERROR_MESSAGE);  
63:        return;  
64:      }  
65:      imagePanel.setImage(currentImage);  
66:      setButtonsEnabled(true);  
67:      showFilename(selectedFile.getPath());  
68:      showStatus("File loaded.");  
69:      frame.pack();  
70:    }  
71:    /**  
72:     * Close function: close the current image.  
73:     */  
74:    private void close()  
75:    {  
76:      currentImage = null;  
77:      imagePanel.clearImage();  
78:      showFilename(null);  
79:      setButtonsEnabled(false);  
80:    }  
81:    /**  
82:     * Save As function: save the current image to a file.  
83:     */  
84:    private void saveAs()  
85:    {  
86:      if(currentImage != null) {  
87:        int returnVal = fileChooser.showSaveDialog(frame);  
88:        if(returnVal != JFileChooser.APPROVE_OPTION) {  
89:          return; // cancelled  
90:        }  
91:        File selectedFile = fileChooser.getSelectedFile();  
92:        ImageFileManager.saveImage(currentImage, selectedFile);  
93:        showFilename(selectedFile.getPath());  
94:      }  
95:    }  
96:    /**  
97:     * Quit function: quit the application.  
98:     */  
99:    private void quit()  
100:    {  
101:      System.exit(0);  
102:    }  
103:    /**  
104:     * Apply a given filter to the current image.  
105:     *   
106:     * @param filter  The filter object to be applied.  
107:     */  
108:    private void applyFilter(Filter filter)  
109:    {  
110:      if(currentImage != null) {  
111:        filter.apply(currentImage);  
112:        frame.repaint();  
113:        showStatus("Applied: " + filter.getName());  
114:      }  
115:      else {  
116:        showStatus("No image loaded.");  
117:      }  
118:    }  
119:    /**  
120:     * 'About' function: show the 'about' box.  
121:     */  
122:    private void showAbout()  
123:    {  
124:      JOptionPane.showMessageDialog(frame,   
125:            "ImageViewer\n" + VERSION,  
126:            "About ImageViewer",   
127:            JOptionPane.INFORMATION_MESSAGE);  
128:    }  
129:    /**  
130:     * Make the current picture larger.  
131:     */  
132:    private void makeLarger()  
133:    {  
134:      if(currentImage != null) {  
135:        // create new image with double size  
136:        int width = currentImage.getWidth();  
137:        int height = currentImage.getHeight();  
138:        OFImage newImage = new OFImage(width * 2, height * 2);  
139:        // copy pixel data into new image  
140:        for(int y = 0; y < height; y++) {  
141:          for(int x = 0; x < width; x++) {  
142:            Color col = currentImage.getPixel(x, y);  
143:            newImage.setPixel(x * 2, y * 2, col);  
144:            newImage.setPixel(x * 2 + 1, y * 2, col);  
145:            newImage.setPixel(x * 2, y * 2 + 1, col);  
146:            newImage.setPixel(x * 2+1, y * 2 + 1, col);  
147:          }  
148:        }  
149:        currentImage = newImage;  
150:        imagePanel.setImage(currentImage);  
151:        frame.pack();  
152:      }  
153:    }  
154:    /**  
155:     * Make the current picture smaller.  
156:     */  
157:    private void makeSmaller()  
158:    {  
159:      if(currentImage != null) {  
160:        // create new image with double size  
161:        int width = currentImage.getWidth() / 2;  
162:        int height = currentImage.getHeight() / 2;  
163:        OFImage newImage = new OFImage(width, height);  
164:        // copy pixel data into new image  
165:        for(int y = 0; y < height; y++) {  
166:          for(int x = 0; x < width; x++) {  
167:            newImage.setPixel(x, y, currentImage.getPixel(x * 2, y * 2));  
168:          }  
169:        }  
170:        currentImage = newImage;  
171:        imagePanel.setImage(currentImage);  
172:        frame.pack();  
173:      }  
174:    }  
175:    private void cropImage(){  
176:      if(currentImage!=null){  
177:        int x_max = currentImage.getWidth();  
178:        int y_max = currentImage.getHeight();  
179:        Point min = cropEvent.getMinPoint();  
180:        Point max = cropEvent.getMaxPoint();  
181:        try {  
182:  //        BufferedImage croppedImage = currentImage.getSubimage( 20 , 12, 140, 150);  
183:          OFImage subimage = new OFImage(max.x - min.x, max.y - min.y);  
184:          for (int y = 0; y < max.y - min.y; y++)  
185:          {  
186:            for (int x = 0; x < max.x - min.x; x++)  
187:            {  
188:              subimage.setPixel(x, y, currentImage.getPixel(x + min.x, y + min.y));  
189:            }  
190:          }  
191:          currentImage = subimage;  
192:          imagePanel.setImage(currentImage);  
193:          frame.pack();  
194:        }  
195:        catch (Exception e) {  
196:          e.printStackTrace();  
197:          JOptionPane.showMessageDialog(null, "Selection Out Of Bound","Error", JOptionPane.OK_OPTION);  
198:        }  
199:      }  
200:    }  
201:    // ---- support methods ----  
202:    /**  
203:     * Show the file name of the current image in the fils display label.  
204:     * 'null' may be used as a parameter if no file is currently loaded.  
205:     *   
206:     * @param filename The file name to be displayed, or null for 'no file'.  
207:     */  
208:    private void showFilename(String filename)  
209:    {  
210:      if(filename == null) {  
211:        filenameLabel.setText("No file displayed.");  
212:      }  
213:      else {  
214:        filenameLabel.setText("File: " + filename);  
215:      }  
216:    }  
217:    /**  
218:     * Show a message in the status bar at the bottom of the screen.  
219:     * @param text The message to be displayed.  
220:     */  
221:    private void showStatus(String text)  
222:    {  
223:      statusLabel.setText(text);  
224:    }  
225:    /**  
226:     * Enable or disable all toolbar buttons.  
227:     *   
228:     * @param status 'true' to enable the buttons, 'false' to disable.  
229:     */  
230:    private void setButtonsEnabled(boolean status)  
231:    {  
232:      smallerButton.setEnabled(status);  
233:      largerButton.setEnabled(status);  
234:      cropButton.setEnabled(status);  
235:    }  
236:    /**  
237:     * Create a list with all the known filters.  
238:     * @return The list of filters.  
239:     */  
240:    private List<Filter> createFilters()  
241:    {  
242:      List<Filter> filterList = new ArrayList<Filter>();  
243:      filterList.add(new DarkerFilter("Darker"));  
244:      filterList.add(new LighterFilter("Lighter"));  
245:      filterList.add(new ThresholdFilter("Threshold"));  
246:      filterList.add(new FishEyeFilter("Fish Eye"));  
247:      return filterList;  
248:    }  
249:    // ---- swing stuff to build the frame and all its components ----  
250:    /**  
251:     * Create the Swing frame and its content.  
252:     */  
253:    private void makeFrame()  
254:    {  
255:      frame = new JFrame("ImageViewer");  
256:      JPanel contentPane = (JPanel)frame.getContentPane();  
257:      contentPane.setBorder(new EmptyBorder(6, 6, 6, 6));  
258:      makeMenuBar(frame);  
259:      // Specify the layout manager with nice spacing  
260:      contentPane.setLayout(new BorderLayout(6, 6));  
261:      // Create the image pane in the center  
262:      imagePanel = new ImagePanel();  
263:      imagePanel.setBorder(new EtchedBorder());  
264:      cropEvent = new CropEvent(imagePanel);  
265:      JScrollPane scroller = new JScrollPane(imagePanel);  
266:      scroller.setPreferredSize(Toolkit.getDefaultToolkit().getScreenSize());  
267:      contentPane.add(scroller, BorderLayout.CENTER);  
268:      // Create two labels at top and bottom for the file name and status message  
269:      filenameLabel = new JLabel();  
270:      contentPane.add(filenameLabel, BorderLayout.NORTH);  
271:      statusLabel = new JLabel(VERSION);  
272:      contentPane.add(statusLabel, BorderLayout.SOUTH);  
273:      // Create the toolbar with the buttons  
274:      JPanel toolbar = new JPanel();  
275:      toolbar.setLayout(new GridLayout(0, 1));  
276:      smallerButton = new JButton("Smaller");  
277:      smallerButton.addActionListener(new ActionListener() {  
278:                  public void actionPerformed(ActionEvent e) { makeSmaller(); }  
279:                });  
280:      toolbar.add(smallerButton);  
281:      largerButton = new JButton("Larger");  
282:      largerButton.addActionListener(new ActionListener() {  
283:                  public void actionPerformed(ActionEvent e) { makeLarger(); }  
284:                });  
285:      toolbar.add(largerButton);  
286:      cropButton = new JToggleButton("Crop");  
287:      cropButton.addActionListener(new ActionListener() {  
288:        public void actionPerformed(ActionEvent e) {  
289:          if(cropButton.isSelected()){  
290:            cropEvent.addEvent();  
291:          }  
292:          else{  
293:            cropEvent.removeEvent();  
294:            cropImage();  
295:          }  
296:        }  
297:      });  
298:      toolbar.add(cropButton);  
299:      // Add toolbar into panel with flow layout for spacing  
300:      JPanel flow = new JPanel();  
301:      flow.add(toolbar);  
302:      contentPane.add(flow, BorderLayout.WEST);  
303:      // building is done - arrange the components  
304:      showFilename(null);  
305:      setButtonsEnabled(false);  
306:      frame.pack();  
307:      // place the frame at the center of the screen and show  
308:      Dimension d = Toolkit.getDefaultToolkit().getScreenSize();  
309:      frame.setLocation(d.width/2 - frame.getWidth()/2, d.height/2 - frame.getHeight()/2);  
310:      frame.setVisible(true);  
311:    }  
312:    /**  
313:     * Create the main frame's menu bar.  
314:     *  
315:     * @param frame  The frame that the menu bar should be added to.  
316:     */  
317:    private void makeMenuBar(JFrame frame)  
318:    {  
319:      final int SHORTCUT_MASK =  
320:        Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();  
321:      JMenuBar menubar = new JMenuBar();  
322:      frame.setJMenuBar(menubar);  
323:      JMenu menu;  
324:      JMenuItem item;  
325:      // create the File menu  
326:      menu = new JMenu("File");  
327:      menubar.add(menu);  
328:      item = new JMenuItem("Open...");  
329:        item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, SHORTCUT_MASK));  
330:        item.addActionListener(new ActionListener() {  
331:                  public void actionPerformed(ActionEvent e) { openFile(); }  
332:                });  
333:      menu.add(item);  
334:      item = new JMenuItem("Close");  
335:        item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, SHORTCUT_MASK));  
336:        item.addActionListener(new ActionListener() {  
337:                  public void actionPerformed(ActionEvent e) { close(); }  
338:                });  
339:      menu.add(item);  
340:      menu.addSeparator();  
341:      item = new JMenuItem("Save As...");  
342:        item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, SHORTCUT_MASK));  
343:        item.addActionListener(new ActionListener() {  
344:                  public void actionPerformed(ActionEvent e) { saveAs(); }  
345:                });  
346:      menu.add(item);  
347:      menu.addSeparator();  
348:      item = new JMenuItem("Quit");  
349:        item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, SHORTCUT_MASK));  
350:        item.addActionListener(new ActionListener() {  
351:                  public void actionPerformed(ActionEvent e) { quit(); }  
352:                });  
353:      menu.add(item);  
354:      // create the Filter menu  
355:      menu = new JMenu("Filter");  
356:      menubar.add(menu);  
357:      for(final Filter filter : filters) {  
358:        item = new JMenuItem(filter.getName());  
359:        item.addActionListener(new ActionListener() {  
360:                  public void actionPerformed(ActionEvent e) {   
361:                    applyFilter(filter);  
362:                  }  
363:                });  
364:         menu.add(item);  
365:       }  
366:      // create the Help menu  
367:      menu = new JMenu("Help");  
368:      menubar.add(menu);  
369:      item = new JMenuItem("About ImageViewer...");  
370:        item.addActionListener(new ActionListener() {  
371:                  public void actionPerformed(ActionEvent e) { showAbout(); }  
372:                });  
373:      menu.add(item);  
374:    }  
375:  }  


2. Image Panel
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 Michael Kolling and David J. Barnes  
11:   * @version 1.0  
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:  }  


3. 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 Michael Kolling and David J. Barnes  
8:   * @version 2.0  
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:  }  


4. Image File Manager
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 Michael Kolling and David J Barnes   
12:   * @version 2.0  
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:  }  


5. Filter
1:  /**  
2:   * Filter is an abstract superclass for all image filters in this  
3:   * application. Filters can be applied to OFImages by invoking the apply   
4:   * method.  
5:   *   
6:   * @author Michael Kolling and David J Barnes   
7:   * @version 1.0  
8:   */  
9:  public abstract class Filter  
10:  {  
11:    private String name;  
12:    /**  
13:     * Create a new filter with a given name.  
14:     * @param name The name of the filter.  
15:     */  
16:    public Filter(String name)  
17:    {  
18:      this.name = name;  
19:    }  
20:    /**  
21:     * Return the name of this filter.  
22:     *   
23:     * @return The name of this filter.  
24:     */  
25:    public String getName()  
26:    {  
27:      return name;  
28:    }  
29:    /**  
30:     * Apply this filter to an image.  
31:     *   
32:     * @param image The image to be changed by this filter.  
33:     */  
34:    public abstract void apply(OFImage image);  
35:  }  


6. Darker Filter
1:  /**  
2:   * An image filter to make the image a bit darker.  
3:   *   
4:   * @author Michael Kolling and David J Barnes   
5:   * @version 1.0  
6:   */  
7:  public class DarkerFilter extends Filter  
8:  {  
9:    /**  
10:     * Constructor for objects of class DarkerFilter.  
11:     * @param name The name of the filter.  
12:     */  
13:    public DarkerFilter(String name)  
14:    {  
15:      super(name);  
16:    }  
17:    /**  
18:     * Apply this filter to an image.  
19:     *   
20:     * @param image The image to be changed by this filter.  
21:     */  
22:    public void apply(OFImage image)  
23:    {  
24:      int height = image.getHeight();  
25:      int width = image.getWidth();  
26:      for(int y = 0; y < height; y++) {  
27:        for(int x = 0; x < width; x++) {  
28:          image.setPixel(x, y, image.getPixel(x, y).darker());  
29:        }  
30:      }  
31:    }  
32:  }  


7. Fish Eye Filter
1:  import java.awt.Color;  
2:  /**  
3:   * An image filter to create an effect similar to a fisheye camera lens.  
4:   * (Works especially well on portraits.)  
5:   *   
6:   * @author Michael Kolling and David J Barnes   
7:   * @version 1.0  
8:   */  
9:  public class FishEyeFilter extends Filter  
10:  {  
11:    // constants:  
12:    private final static int SCALE = 20;  // this defines the strenght of the filter  
13:    private final static double TWO_PI = 2 * Math.PI;  
14:    /**  
15:     * Constructor for objects of class LensFilter.  
16:     * @param name The name of the filter.  
17:     */  
18:    public FishEyeFilter(String name)  
19:    {  
20:      super(name);  
21:    }  
22:    /**  
23:     * Apply this filter to an image.  
24:     *   
25:     * @param image The image to be changed by this filter.  
26:     */  
27:    public void apply(OFImage image)  
28:    {  
29:      int height = image.getHeight();  
30:      int width = image.getWidth();  
31:      OFImage original = new OFImage(image);  
32:      int[] xa = computeXArray(width);  
33:      int[] ya = computeYArray(height);  
34:      for(int y = 0; y < height; y++) {  
35:        for(int x = 0; x < width; x++) {  
36:          image.setPixel(x, y, original.getPixel(x + xa[x], y + ya[y]));  
37:        }  
38:      }  
39:    }  
40:    /**  
41:     * Compute and return an array of horizontal offsets for each pixel column.  
42:     * These can then be applied as the horizontal offset for each pixel.  
43:     */  
44:    private int[] computeXArray(int width)  
45:    {  
46:      int[] xArray = new int[width];  
47:      for(int i=0; i < width; i++) {  
48:        xArray[i] = (int)(Math.sin( ((double)i / width) * TWO_PI) * SCALE);  
49:      }  
50:      return xArray;  
51:    }  
52:    /**  
53:     * Compute and return an array of vertical offsets for each pixel row.  
54:     * These can then be applied as the vertical offset for each pixel.  
55:     */  
56:    private int[] computeYArray(int height)  
57:    {  
58:      int[] yArray = new int[height];  
59:      for(int i=0; i < height; i++) {  
60:        yArray[i] = (int)(Math.sin( ((double)i / height) * TWO_PI) * SCALE);  
61:      }  
62:      return yArray;  
63:    }  
64:  }  


8. Lighter Filter
1:  /**  
2:   * An image filter to make the image a bit lighter.  
3:   *   
4:   * @author Michael Kolling and David J Barnes   
5:   * @version 1.0  
6:   */  
7:  public class LighterFilter extends Filter  
8:  {  
9:       /**  
10:        * Constructor for objects of class LighterFilter.  
11:     * @param name The name of the filter.  
12:        */  
13:       public LighterFilter(String name)  
14:    {  
15:      super(name);  
16:       }  
17:    /**  
18:     * Apply this filter to an image.  
19:     *   
20:     * @param image The image to be changed by this filter.  
21:     */  
22:    public void apply(OFImage image)  
23:    {  
24:      int height = image.getHeight();  
25:      int width = image.getWidth();  
26:      for(int y = 0; y < height; y++) {  
27:        for(int x = 0; x < width; x++) {  
28:          image.setPixel(x, y, image.getPixel(x, y).brighter());  
29:        }  
30:      }  
31:    }  
32:  }  


9. Threshold Filter
1:  import java.awt.Color;  
2:  /**  
3:   * An three-level gray-based threshold filter.  
4:   *   
5:   * @author Michael Kolling and David J Barnes   
6:   * @version 1.0  
7:   */  
8:  public class ThresholdFilter extends Filter  
9:  {  
10:       /**  
11:        * Constructor for objects of class ThresholdFilter.  
12:     * @param name The name of the filter.  
13:        */  
14:       public ThresholdFilter(String name)  
15:    {  
16:      super(name);  
17:       }  
18:    /**  
19:     * Apply this filter to an image.  
20:     *   
21:     * @param image The image to be changed by this filter.  
22:     */  
23:    public void apply(OFImage image)  
24:    {  
25:      int height = image.getHeight();  
26:      int width = image.getWidth();  
27:      for(int y = 0; y < height; y++) {  
28:        for(int x = 0; x < width; x++) {  
29:          Color pixel = image.getPixel(x, y);  
30:          int brightness = (pixel.getRed() + pixel.getBlue() + pixel.getGreen()) / 3;  
31:          if(brightness <= 85) {  
32:            image.setPixel(x, y, Color.BLACK);  
33:          }  
34:          else if(brightness <= 170) {  
35:            image.setPixel(x, y, Color.GRAY);  
36:          }  
37:          else {  
38:            image.setPixel(x, y, Color.WHITE);  
39:          }  
40:        }  
41:      }  
42:    }  
43:  }  

10. CropEvent

1:  import java.awt.*;  
2:  import java.awt.event.MouseAdapter;  
3:  import java.awt.event.MouseEvent;  
4:  import java.awt.event.MouseListener;  
5:  public class CropEvent{  
6:    private ImagePanel imagePanel;  
7:    private Point point1;  
8:    private Point point2;  
9:    private Point min;  
10:    private Point max;  
11:    public CropEvent(ImagePanel imagePanel){  
12:       this.imagePanel = imagePanel;  
13:    }  
14:    public Point getMinPoint(){return min;}  
15:    public Point getMaxPoint(){return max;}  
16:    private void calculatePoint(){  
17:      int x = (point1.x > point2.x) ? point2.x : point1.x;  
18:      int y = (point1.y > point2.y) ? point2.y : point1.y;  
19:      min = new Point(x,y);  
20:      max = new Point(x + (Math.abs(point1.x-point2.x)),y+(Math.abs(point1.y-point2.y)));  
21:    }  
22:    public void removeEvent(){  
23:      MouseListener[] mouseListener = imagePanel.getMouseListeners();  
24:      for(MouseListener ms : mouseListener){  
25:        imagePanel.removeMouseListener(ms);  
26:      }  
27:    }  
28:    public void addEvent(){  
29:      imagePanel.addMouseListener(new MouseAdapter() {  
30:        public void mouseEntered(MouseEvent e) {  
31:  //        System.out.println("Enter");  
32:          imagePanel.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));  
33:        }  
34:        public void mouseExited(MouseEvent e) {  
35:  //        System.out.println("Exit99");  
36:          imagePanel.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));  
37:        }  
38:        public void mousePressed(MouseEvent e) {  
39:          point1 = e.getPoint();  
40:        }  
41:        public void mouseReleased(MouseEvent e) {  
42:          point2 = e.getPoint();  
43:          calculatePoint();  
44:        }  
45:      });  
46:    }  
47:  }  

Sekarang kita jalankan class Image Viewer dan viola, jadilah aplikasi Image Viewer kita.

Komentar

Postingan populer dari blog ini

Pong Java Game

Java GUI Image Viewer