Rabu, 13 November 2019

Program Image Viewer Menggunakan Java

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

Output Program :
1. Tampilan awal program

2. Gambar berhasil diinsert ke program

3. Tampilan gambar pada filter darker

4. Tampilan gambar pada filter lighter

5. Tampilan gambar pada filter treshold

Tidak ada komentar:

Posting Komentar