Advertisement
igede

Untitled

Dec 10th, 2018
223
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 18.22 KB | None | 0 0
  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import java.awt.image.*;
  4. import javax.swing.*;
  5. import javax.swing.border.*;
  6.  
  7. import java.io.File;
  8.  
  9. import java.util.List;
  10. import java.util.ArrayList;
  11. import java.util.Iterator;
  12.  
  13. import java.util.Scanner;
  14.  
  15.  
  16.  
  17. /**
  18.  * ImageViewer is the main class of the image viewer application. It builds and
  19.  * displays the application GUI and initialises all other components.
  20.  *
  21.  * To start the application, create an object of this class.
  22.  *
  23.  * @author Gede
  24.  * @version (10/12/2018)
  25.  */
  26. public class ImageViewer
  27. {
  28.     // static fields:
  29.     private static final String VERSION = "Version 3.0";
  30.     private static JFileChooser fileChooser = new JFileChooser(System.getProperty("user.dir"));
  31.  
  32.     // fields:
  33.     private JFrame frame;
  34.     private ImagePanel imagePanel;
  35.     private JLabel filenameLabel;
  36.     private JLabel statusLabel;
  37.     private JButton smallerButton;
  38.     private JButton largerButton;
  39.     private JButton resizeButton;
  40.     private JButton cropButton;
  41.     private JButton textButton;
  42.     private OFImage currentImage;
  43.    
  44.     private List<Filter> filters;
  45.    
  46.     /**
  47.      * Create an ImageViewer and display its GUI on screen.
  48.      */
  49.     public ImageViewer()
  50.     {
  51.         currentImage = null;
  52.         filters = createFilters();
  53.         makeFrame();
  54.     }
  55.  
  56.  
  57.     // ---- implementation of menu functions ----
  58.    
  59.     /**
  60.      * Open function: open a file chooser to select a new image file,
  61.      * and then display the chosen image.
  62.      */
  63.     private void openFile()
  64.     {
  65.         int returnVal = fileChooser.showOpenDialog(frame);
  66.  
  67.         if(returnVal != JFileChooser.APPROVE_OPTION) {
  68.             return;  // cancelled
  69.         }
  70.         File selectedFile = fileChooser.getSelectedFile();
  71.         currentImage = ImageFileManager.loadImage(selectedFile);
  72.        
  73.         if(currentImage == null) {   // image file was not a valid image
  74.             JOptionPane.showMessageDialog(frame,
  75.                     "The file was not in a recognized image file format.",
  76.                     "Image Load Error",
  77.                     JOptionPane.ERROR_MESSAGE);
  78.             return;
  79.         }
  80.  
  81.         imagePanel.setImage(currentImage);
  82.         setButtonsEnabled(true);
  83.         showFilename(selectedFile.getPath());
  84.         showStatus("File loaded.");
  85.         frame.pack();
  86.     }
  87.  
  88.     /**
  89.      * Close function: close the current image.
  90.      */
  91.     private void close()
  92.     {
  93.         currentImage = null;
  94.         imagePanel.clearImage();
  95.         showFilename(null);
  96.         setButtonsEnabled(false);
  97.     }
  98.  
  99.     /**
  100.      * Save As function: save the current image to a file.
  101.      */
  102.     private void saveAs()
  103.     {
  104.         if(currentImage != null) {
  105.             int returnVal = fileChooser.showSaveDialog(frame);
  106.    
  107.             if(returnVal != JFileChooser.APPROVE_OPTION) {
  108.                 return;  // cancelled
  109.             }
  110.             File selectedFile = fileChooser.getSelectedFile();
  111.             ImageFileManager.saveImage(currentImage, selectedFile);
  112.            
  113.             showFilename(selectedFile.getPath());
  114.         }
  115.     }
  116.  
  117.     /**
  118.      * Quit function: quit the application.
  119.      */
  120.     private void quit()
  121.     {
  122.         System.exit(0);
  123.     }
  124.  
  125.     /**
  126.      * Apply a given filter to the current image.
  127.      *
  128.      * @param filter   The filter object to be applied.
  129.      */
  130.     private void applyFilter(Filter filter)
  131.     {
  132.         if(currentImage != null) {
  133.             filter.apply(currentImage);
  134.             frame.repaint();
  135.             showStatus("Applied: " + filter.getName());
  136.         }
  137.         else {
  138.             showStatus("No image loaded.");
  139.         }
  140.     }
  141.    
  142.     private void crop()
  143.     {
  144.         if (currentImage != null)
  145.         {
  146.             int width = currentImage.getWidth();
  147.             int height = currentImage.getWidth();
  148.             int xAwal = Integer.parseInt(JOptionPane.showInputDialog("xAwal"));
  149.             int yAwal = Integer.parseInt(JOptionPane.showInputDialog("yAwal"));
  150.             int xAkhir = Integer.parseInt(JOptionPane.showInputDialog("xAkhir"));
  151.             int yAkhir = Integer.parseInt(JOptionPane.showInputDialog("yAkhir"));
  152.             OFImage newImage = new OFImage(xAkhir - xAwal, yAkhir - yAwal);
  153.            
  154.             for (int y = 0; y < yAkhir - yAwal; y++)
  155.             {
  156.                 for (int x = 0; x < xAkhir - xAwal; x++)
  157.                 {
  158.                     newImage.setPixel(x, y, currentImage.getPixel(x + xAwal, y + yAwal));
  159.                 }
  160.             }
  161.            
  162.             currentImage = newImage;
  163.             imagePanel.setImage(currentImage);
  164.             frame.pack();
  165.         }
  166.     }
  167.    
  168.     private void makeText()
  169.     {
  170.         JTextField xField = new JTextField(5);
  171.         JTextField yField = new JTextField(5);
  172.         JTextField zField = new JTextField(5);
  173.        
  174.         JPanel myPanel = new JPanel();
  175.         myPanel.add(new JLabel("R"));
  176.         myPanel.add(xField);
  177.         myPanel.add(Box.createVerticalStrut(15)); // a spacer
  178.         myPanel.add(new JLabel("G"));
  179.         myPanel.add(yField);
  180.         myPanel.add(Box.createVerticalStrut(15)); // a spacer
  181.         myPanel.add(new JLabel("B"));
  182.         myPanel.add(zField);
  183.         if(currentImage != null) {
  184.             int width = currentImage.getWidth();
  185.             int height = currentImage.getHeight();
  186.             int xPosition = Integer.parseInt(JOptionPane.showInputDialog("Pixel Position X"));
  187.             int yPosition = Integer.parseInt(JOptionPane.showInputDialog("Pixel Position Y"));
  188.             float fontSize = Float.parseFloat(JOptionPane.showInputDialog("Font Size"));
  189.             String addText = JOptionPane.showInputDialog("Write Something..");
  190.             int result = JOptionPane.showConfirmDialog(null, myPanel, "Font Color", JOptionPane.OK_CANCEL_OPTION);
  191.             OFImage newImage = new OFImage(width, height);
  192.            
  193.             // copy pixel data into new image
  194.             for(int y = 0; y < height; y++) {
  195.                 for(int x = 0; x < width; x++) {
  196.                     Color col = currentImage.getPixel(x, y);
  197.                     newImage.setPixel(x, y, col);
  198.                 }
  199.             }
  200.            
  201.             int r = Integer.parseInt(xField.getText());
  202.             int gr = Integer.parseInt(yField.getText());
  203.             int b = Integer.parseInt(zField.getText());
  204.             Color c = new Color(r,gr,b);
  205.             Graphics g = newImage.getGraphics();
  206.             g.setFont(g.getFont().deriveFont(fontSize));
  207.             g.setColor(c);
  208.             g.drawString(addText, xPosition, yPosition);
  209.             g.dispose();
  210.            
  211.             currentImage = newImage;
  212.             imagePanel.setImage(currentImage);
  213.         }
  214.     }
  215.    
  216.     /**
  217.      * 'About' function: show the 'about' box.
  218.      */
  219.     private void showAbout()
  220.     {
  221.         JOptionPane.showMessageDialog(frame,
  222.                     "ImageViewer\n" + VERSION,
  223.                     "About ImageViewer",
  224.                     JOptionPane.INFORMATION_MESSAGE);
  225.     }
  226.  
  227.     /**
  228.      * Make the current picture larger.
  229.      */
  230.    
  231.            
  232.     private void makeLarger()
  233.     {
  234.         if(currentImage != null) {
  235.             // create new image with double size
  236.             int width = currentImage.getWidth();
  237.             int height = currentImage.getHeight();
  238.  
  239.             OFImage newImage = new OFImage(width * 2, height * 2);
  240.  
  241.             // copy pixel data into new image
  242.             for(int y = 0; y < height; y++) {
  243.                 for(int x = 0; x < width; x++) {
  244.                     Color col = currentImage.getPixel(x, y);
  245.                     newImage.setPixel(x * 2, y * 2, col);
  246.                     newImage.setPixel(x * 2 + 1, y * 2, col);
  247.                     newImage.setPixel(x * 2, y * 2 + 1, col);
  248.                     newImage.setPixel(x * 2+1, y * 2 + 1, col);
  249.                 }
  250.             }
  251.            
  252.             currentImage = newImage;
  253.             imagePanel.setImage(currentImage);
  254.             frame.pack();
  255.         }
  256.     }
  257.  
  258.     /**
  259.      * Make the current picture smaller.
  260.      */
  261.     private void makeSmaller()
  262.     {
  263.         if(currentImage != null) {
  264.             // create new image with double size
  265.             int width = currentImage.getWidth() / 2;
  266.             int height = currentImage.getHeight() / 2;
  267.             OFImage newImage = new OFImage(width, height);
  268.  
  269.             // copy pixel data into new image
  270.             for(int y = 0; y < height; y++) {
  271.                 for(int x = 0; x < width; x++) {
  272.                     newImage.setPixel(x, y, currentImage.getPixel(x * 2, y * 2));
  273.                 }
  274.             }
  275.            
  276.             currentImage = newImage;
  277.             imagePanel.setImage(currentImage);
  278.             frame.pack();
  279.         }
  280.     }
  281.    
  282.    
  283.         private void Rotate90left() {
  284.         if(currentImage != null) {
  285.             // create new image with double size
  286.             int width = currentImage.getWidth();
  287.             int height = currentImage.getHeight();
  288.             OFImage newImage = new OFImage(height, width);
  289.            
  290.             //copy pixel data into new image
  291.             for(int y = 0; y < height; y++) {
  292.                 for(int x = 0; x < width; x++) {
  293.                     Color col = currentImage.getPixel(x, y);
  294.                     newImage.setPixel(y, width-x-1, col);
  295.                 }
  296.             }
  297.            
  298.             currentImage = newImage;
  299.             imagePanel.setImage(currentImage);
  300.             frame.pack();
  301.         }
  302.     }
  303.    
  304.             private void Rotate90right() {
  305.         if(currentImage != null) {
  306.             // create new image with double size
  307.             int width = currentImage.getWidth();
  308.             int height = currentImage.getHeight();
  309.             OFImage newImage = new OFImage(height, width);
  310.            
  311.             //copy pixel data into new image
  312.             for(int y = 0; y < height; y++) {
  313.                 for(int x = 0; x < width; x++) {
  314.                     Color col = currentImage.getPixel(x, y);
  315.                     newImage.setPixel(height-y-1, x, col);
  316.                 }
  317.             }
  318.            
  319.             currentImage = newImage;
  320.             imagePanel.setImage(currentImage);
  321.             frame.pack();
  322.         }
  323.     }
  324.     // ---- support methods ----
  325.  
  326.     /**
  327.      * Show the file name of the current image in the fils display label.
  328.      * 'null' may be used as a parameter if no file is currently loaded.
  329.      *
  330.      * @param filename  The file name to be displayed, or null for 'no file'.
  331.      */
  332.     private void showFilename(String filename)
  333.     {
  334.         if(filename == null) {
  335.             filenameLabel.setText("No file displayed.");
  336.         }
  337.         else {
  338.             filenameLabel.setText("File: " + filename);
  339.         }
  340.     }
  341.  
  342.     /**
  343.      * Show a message in the status bar at the bottom of the screen.
  344.      * @param text The message to be displayed.
  345.      */
  346.     private void showStatus(String text)
  347.     {
  348.         statusLabel.setText(text);
  349.     }
  350.  
  351.     /**
  352.      * Enable or disable all toolbar buttons.
  353.      *
  354.      * @param status  'true' to enable the buttons, 'false' to disable.
  355.      */
  356.     private void setButtonsEnabled(boolean status)
  357.     {
  358.         smallerButton.setEnabled(status);
  359.         largerButton.setEnabled(status);
  360.         cropButton.setEnabled(status);
  361.         textButton.setEnabled(status);
  362.     }
  363.  
  364.     /**
  365.      * Create a list with all the known filters.
  366.      * @return The list of filters.
  367.      */
  368.     private List<Filter> createFilters()
  369.     {
  370.         List<Filter> filterList = new ArrayList<Filter>();
  371.         filterList.add(new DarkerFilter("Darker"));
  372.         filterList.add(new LighterFilter("Lighter"));
  373.         filterList.add(new ThresholdFilter("Threshold"));
  374.         filterList.add(new FishEyeFilter("Fish Eye"));
  375.         filterList.add(new FlipVerticalFilter("Flip Vertical"));
  376.         filterList.add(new FlipHorizontalFilter("Flip Horizontal"));
  377.        
  378.         return filterList;
  379.     }
  380.    
  381.     // ---- swing stuff to build the frame and all its components ----
  382.    
  383.     /**
  384.      * Create the Swing frame and its content.
  385.      */
  386.     private void makeFrame()
  387.     {
  388.         frame = new JFrame("ImageViewer");
  389.         JPanel contentPane = (JPanel)frame.getContentPane();
  390.         contentPane.setBorder(new EmptyBorder(6, 6, 6, 6));
  391.  
  392.         makeMenuBar(frame);
  393.        
  394.         // Specify the layout manager with nice spacing
  395.         contentPane.setLayout(new BorderLayout(6, 6));
  396.  
  397.         // Create the image pane in the center
  398.         imagePanel = new ImagePanel();
  399.         imagePanel.setBorder(new EtchedBorder());
  400.         contentPane.add(imagePanel, BorderLayout.CENTER);
  401.        
  402.         // Create two labels at top and bottom for the file name and status message
  403.         filenameLabel = new JLabel();
  404.         contentPane.add(filenameLabel, BorderLayout.NORTH);
  405.  
  406.         statusLabel = new JLabel(VERSION);
  407.         contentPane.add(statusLabel, BorderLayout.SOUTH);
  408.        
  409.         // Create the toolbar with the buttons
  410.         JPanel toolbar = new JPanel();
  411.         toolbar.setLayout(new GridLayout(0, 1));
  412.        
  413.         smallerButton = new JButton("Smaller");
  414.         smallerButton.addActionListener(new ActionListener() {
  415.                                public void actionPerformed(ActionEvent e) { makeSmaller(); }
  416.                            });
  417.         toolbar.add(smallerButton);
  418.        
  419.         largerButton = new JButton("Larger");
  420.         largerButton.addActionListener(new ActionListener() {
  421.                                public void actionPerformed(ActionEvent e) { makeLarger(); }
  422.                            });
  423.         toolbar.add(largerButton);
  424.        
  425.         cropButton=new JButton("Crop");
  426.         cropButton.addActionListener(new ActionListener() {
  427.                                public void actionPerformed(ActionEvent e) { crop(); }
  428.                            });
  429.         toolbar.add(cropButton);
  430.        
  431.         textButton=new JButton("MakeText");
  432.         textButton.addActionListener(new ActionListener() {
  433.                                public void actionPerformed(ActionEvent e) { makeText(); }
  434.                            });
  435.         toolbar.add(textButton);
  436.        
  437.         // Add toolbar into panel with flow layout for spacing
  438.         JPanel flow = new JPanel();
  439.         flow.add(toolbar);
  440.        
  441.         contentPane.add(flow, BorderLayout.WEST);
  442.        
  443.         // building is done - arrange the components    
  444.         showFilename(null);
  445.         setButtonsEnabled(false);
  446.         frame.pack();
  447.        
  448.         // place the frame at the center of the screen and show
  449.         Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
  450.         frame.setLocation(d.width/2 - frame.getWidth()/2, d.height/2 - frame.getHeight()/2);
  451.         frame.setVisible(true);
  452.     }
  453.    
  454.     /**
  455.      * Create the main frame's menu bar.
  456.      *
  457.      * @param frame   The frame that the menu bar should be added to.
  458.      */
  459.     private void makeMenuBar(JFrame frame)
  460.     {
  461.         final int SHORTCUT_MASK =
  462.             Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
  463.  
  464.         JMenuBar menubar = new JMenuBar();
  465.         frame.setJMenuBar(menubar);
  466.        
  467.         JMenu menu;
  468.         JMenuItem item;
  469.        
  470.         // create the File menu
  471.         menu = new JMenu("File");
  472.         menubar.add(menu);
  473.        
  474.         item = new JMenuItem("Open...");
  475.             item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, SHORTCUT_MASK));
  476.             item.addActionListener(new ActionListener() {
  477.                                public void actionPerformed(ActionEvent e) { openFile(); }
  478.                            });
  479.         menu.add(item);
  480.  
  481.         item = new JMenuItem("Close");
  482.             item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, SHORTCUT_MASK));
  483.             item.addActionListener(new ActionListener() {
  484.                                public void actionPerformed(ActionEvent e) { close(); }
  485.                            });
  486.         menu.add(item);
  487.         menu.addSeparator();
  488.  
  489.         item = new JMenuItem("Save As...");
  490.             item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, SHORTCUT_MASK));
  491.             item.addActionListener(new ActionListener() {
  492.                                public void actionPerformed(ActionEvent e) { saveAs(); }
  493.                            });
  494.         menu.add(item);
  495.         menu.addSeparator();
  496.        
  497.         item = new JMenuItem("Quit");
  498.             item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, SHORTCUT_MASK));
  499.             item.addActionListener(new ActionListener() {
  500.                                public void actionPerformed(ActionEvent e) { quit(); }
  501.                            });
  502.         menu.add(item);
  503.  
  504.         // create the Filter menu
  505.         menu = new JMenu("Filter");
  506.         menubar.add(menu);
  507.        
  508.         for(final Filter filter : filters) {
  509.             item = new JMenuItem(filter.getName());
  510.             item.addActionListener(new ActionListener() {
  511.                                 public void actionPerformed(ActionEvent e) {
  512.                                     applyFilter(filter);
  513.                                 }
  514.                            });
  515.              menu.add(item);
  516.          }
  517.        
  518.          //edit
  519.         menu = new JMenu("Edit");
  520.         menubar.add(menu);
  521.        
  522.         item = new JMenuItem("Rotate 90 Left");
  523.             item.addActionListener(new ActionListener() {
  524.                                public void actionPerformed(ActionEvent e) { Rotate90left(); }
  525.                            });
  526.         menu.add(item);
  527.        
  528.         item = new JMenuItem("Rotate 90 Right");
  529.             item.addActionListener(new ActionListener() {
  530.                                public void actionPerformed(ActionEvent e) { Rotate90right(); }
  531.                            });
  532.         menu.add(item);
  533.         // create the Help menu
  534.         menu = new JMenu("Help");
  535.         menubar.add(menu);
  536.        
  537.         item = new JMenuItem("About ImageViewer...");
  538.             item.addActionListener(new ActionListener() {
  539.                                public void actionPerformed(ActionEvent e) { showAbout(); }
  540.                            });
  541.         menu.add(item);
  542.     }
  543. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement