Advertisement
Guest User

Main.java

a guest
Jul 30th, 2013
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 19.67 KB | None | 0 0
  1. // ImageEncryption
  2. // Made by Ryan Jackman
  3. // Original content. Do not steal
  4. // This is totally a real copywrite
  5.  
  6. import java.awt.Color;
  7. import java.awt.EventQueue;
  8. import java.awt.Image;
  9. import java.awt.TextArea;
  10. import java.awt.event.MouseAdapter;
  11. import java.awt.event.MouseEvent;
  12. import java.awt.image.BufferedImage;
  13. import java.awt.image.ColorModel;
  14. import java.awt.image.WritableRaster;
  15. import java.io.File;
  16. import java.io.FileNotFoundException;
  17. import java.io.FileOutputStream;
  18. import java.io.IOException;
  19. import java.nio.file.Files;
  20. import java.nio.file.Path;
  21. import java.nio.file.Paths;
  22. import java.util.ArrayList;
  23. import java.util.Arrays;
  24. import java.util.List;
  25.  
  26. import javax.imageio.ImageIO;
  27. import javax.swing.GroupLayout;
  28. import javax.swing.GroupLayout.Alignment;
  29. import javax.swing.ImageIcon;
  30. import javax.swing.JButton;
  31. import javax.swing.JCheckBoxMenuItem;
  32. import javax.swing.JFileChooser;
  33. import javax.swing.JFrame;
  34. import javax.swing.JLabel;
  35. import javax.swing.JMenu;
  36. import javax.swing.JMenuBar;
  37. import javax.swing.JMenuItem;
  38. import javax.swing.JOptionPane;
  39. import javax.swing.JSeparator;
  40. import javax.swing.LayoutStyle.ComponentPlacement;
  41. import javax.swing.SwingConstants;
  42. import javax.swing.UIManager;
  43. import javax.swing.border.EtchedBorder;
  44.  
  45. import sun.awt.shell.ShellFolder;
  46.  
  47. public class Main {
  48.  
  49.     private JFrame frame;
  50.     final JFileChooser fc = new JFileChooser();
  51.    
  52.     private JLabel keyImageLabel, codeImageLabel;
  53.     private JLabel fileLabel;
  54.     private TextArea textArea;
  55.    
  56.     private JButton encryptTextButton;
  57.     private JButton decryptButton;
  58.     private JButton encryptFileButton;
  59.     private JMenuItem makeUniqueKeyButton;
  60.  
  61.     private BufferedImage key, code, output;
  62.     private File file;
  63.    
  64.     private JCheckBoxMenuItem useAlphaLayerCheckBox;
  65.  
  66.     public static void main(String[] args) {
  67.         try {
  68.             UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
  69.         } catch (Throwable e) {
  70.             e.printStackTrace();
  71.         }
  72.         EventQueue.invokeLater(new Runnable() {
  73.             public void run() {
  74.                 try {
  75.                     Main window = new Main();
  76.                     window.frame.setVisible(true);
  77.                 } catch (Exception e) {
  78.                     e.printStackTrace();
  79.                 }
  80.             }
  81.         });
  82.     }
  83.  
  84.     public Main() {
  85.         initialize();
  86.     }
  87.  
  88.     private void initialize() {
  89.         frame = new JFrame();
  90.         frame.setBounds(100, 100, 658, 498);
  91.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  92.  
  93.         keyImageLabel = new JLabel("Image Key");
  94.         keyImageLabel.setHorizontalAlignment(SwingConstants.CENTER);
  95.         keyImageLabel.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));
  96.         codeImageLabel = new JLabel("Encoded Image");
  97.         codeImageLabel.setHorizontalAlignment(SwingConstants.CENTER);
  98.         codeImageLabel.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));
  99.         fileLabel = new JLabel("File Icon");
  100.         fileLabel.setHorizontalAlignment(SwingConstants.CENTER);
  101.         fileLabel.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));
  102.        
  103.         encryptTextButton = new JButton("Encrypt Text");
  104.         encryptTextButton.setEnabled(false);
  105.         decryptButton = new JButton("Decrypt Image");
  106.         decryptButton.setEnabled(false);
  107.         encryptFileButton = new JButton("Encrypt File");
  108.         encryptFileButton.setEnabled(false);
  109.        
  110.         JButton loadKeyImageButton = new JButton("Load Key Image");
  111.         JButton loadEncodedImageButton = new JButton("Load Encoded Image");
  112.         JButton btnLoadFile = new JButton("Load File");
  113.        
  114.         // Menu Bar
  115.         JMenuBar menuBar = new JMenuBar();
  116.         frame.setJMenuBar(menuBar);
  117.             JMenu mnFile = new JMenu("File");
  118.             menuBar.add(mnFile);
  119.                 JMenuItem mntmClearAll = new JMenuItem("Clear All");
  120.                 JMenuItem mntmExit = new JMenuItem("Exit");
  121.            
  122.             JMenu mnEdit = new JMenu("Edit");
  123.             menuBar.add(mnEdit);
  124.                 useAlphaLayerCheckBox = new JCheckBoxMenuItem("Use Alpha Layer");
  125.                 mnEdit.add(useAlphaLayerCheckBox);
  126.                 makeUniqueKeyButton = new JMenuItem("Create Unique Key");
  127.                 makeUniqueKeyButton.setEnabled(false);
  128.        
  129.         textArea = new TextArea();
  130.         textArea.setFont(UIManager.getFont("TextArea.font"));
  131.  
  132.         JSeparator separator = new JSeparator();
  133.        
  134.         /********
  135.          * EXIT *
  136.          ********/
  137.  
  138.         mntmExit.addMouseListener(new MouseAdapter() {
  139.             @Override
  140.             public void mouseReleased(MouseEvent e) {
  141.                 System.exit(0);
  142.             }
  143.         });
  144.         mnFile.add(mntmExit);
  145.        
  146.         /*************
  147.          * CLEAR ALL *
  148.          *************/
  149.  
  150.         mntmClearAll.addMouseListener(new MouseAdapter() {
  151.             @Override
  152.             public void mouseReleased(MouseEvent e) {
  153.                 System.out.println("clear");
  154.                 code = null;
  155.                 key = null;
  156.                 file = null;
  157.  
  158.                 keyImageLabel.setIcon(null);
  159.                 keyImageLabel.setText("Image Key");
  160.                 codeImageLabel.setIcon(null);
  161.                 codeImageLabel.setText("Encoded Image");
  162.  
  163.                 textArea.setText("");
  164.  
  165.                 fileLabel.setIcon(null);
  166.                 fileLabel.setText("File Icon");
  167.                
  168.                 encryptFileButton.setEnabled(false);
  169.                 decryptButton.setEnabled(false);
  170.                 encryptTextButton.setEnabled(false);
  171.                 makeUniqueKeyButton.setEnabled(false);
  172.             }
  173.         });
  174.         mnFile.add(mntmClearAll);
  175.        
  176.         /*******************
  177.          * MAKE UNIQUE KEY *
  178.          *******************/
  179.  
  180.         makeUniqueKeyButton.addMouseListener(new MouseAdapter() {
  181.             @Override
  182.             public void mouseReleased(MouseEvent e) {
  183.                 if (key != null) {
  184.                     BufferedImage temp = deepCopy(key);
  185.                     for (int y = 0; y < temp.getHeight(); y++) {
  186.                         for (int x = 0; x < temp.getWidth(); x++) {
  187.                             int rgb = temp.getRGB(x, y);
  188.                             int[] c = { (rgb >> 16) & 0xFF, (rgb >> 8) & 0xFF, (rgb) & 0xFF };
  189.  
  190.                             for (int i = 0; i < 3; i++) {
  191.                                 if (Math.random() > 0.7) {
  192.                                     c[i] += 1;
  193.                                 }
  194.                             }
  195.                         }
  196.                     }
  197.                    
  198.                     File f = null;
  199.                     fc.setSelectedFile(new File("image.png"));
  200.                     int returnVal = fc.showSaveDialog(frame);
  201.  
  202.                     if (returnVal == JFileChooser.APPROVE_OPTION) {
  203.                         f = fc.getSelectedFile();
  204.                      
  205.                         try {
  206.                             ImageIO.write(temp, "png", f);
  207.                         } catch (Exception ex) {
  208.                             ex.printStackTrace();
  209.                         }
  210.                     }
  211.                 }
  212.             }
  213.         });
  214.         mnEdit.add(makeUniqueKeyButton);
  215.  
  216.         /***************
  217.          * LOAD IMAGES *
  218.          ***************/
  219.  
  220.         loadKeyImageButton.addMouseListener(new MouseAdapter() {
  221.             @Override
  222.             public void mouseClicked(MouseEvent e) {
  223.                 key = loadImage();
  224.                 if (key != null) {
  225.                     keyImageLabel.setIcon(getScaledIcon(key, 170, 177));
  226.                     keyImageLabel.setText("");
  227.                    
  228.                     makeUniqueKeyButton.setEnabled(true);
  229.                     encryptTextButton.setEnabled(true);
  230.                     if(code != null)
  231.                         decryptButton.setEnabled(true);
  232.                     if(file != null)
  233.                         encryptFileButton.setEnabled(true);
  234.                 }
  235.             }
  236.         });
  237.  
  238.         loadEncodedImageButton.addMouseListener(new MouseAdapter() {
  239.             @Override
  240.             public void mouseClicked(MouseEvent e) {
  241.                 code = loadImage();
  242.                 if (code != null) {
  243.                     codeImageLabel.setIcon(getScaledIcon(code, 170, 177));
  244.                     codeImageLabel.setText("");
  245.                    
  246.                     if(key != null)
  247.                         decryptButton.setEnabled(true);
  248.                 }
  249.             }
  250.         });
  251.        
  252.         /*************
  253.          * LOAD FILE *
  254.          *************/
  255.  
  256.         btnLoadFile.addMouseListener(new MouseAdapter() {
  257.             @Override
  258.             public void mouseClicked(MouseEvent arg0) {
  259.                 int returnVal = fc.showOpenDialog(frame);
  260.                 if (returnVal == JFileChooser.APPROVE_OPTION) {
  261.                     file = fc.getSelectedFile();
  262.                     try {
  263.                         fileLabel.setIcon(getScaledIcon((BufferedImage) ShellFolder.getShellFolder(file).getIcon(true), 91, 104));
  264.                     } catch (FileNotFoundException e) {
  265.                         e.printStackTrace();
  266.                     }
  267.                     fileLabel.setText("");
  268.                    
  269.                     if(key != null)
  270.                         encryptFileButton.setEnabled(true);
  271.                 }
  272.             }
  273.         });
  274.        
  275.         /*****************
  276.          * DECRYPT IMAGE *
  277.          *****************/
  278.  
  279.         decryptButton.addMouseListener(new MouseAdapter() {
  280.             @Override
  281.             public void mouseClicked(MouseEvent e) {
  282.                 // Byte array for "text"
  283.                 byte[] t = { 116, 101, 120, 116 };
  284.                 byte[] b = decrypt(0);
  285.  
  286.                 if (Arrays.equals(b, t)) {
  287.                     // The image holds text
  288.                     Object[] options = { "Print", "Save", "Cancel" };
  289.                     int n = JOptionPane.showOptionDialog(frame, "This image contains text. What would you like to do?", "Message",
  290.                             JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[2]);
  291.  
  292.                     System.out.println(n);
  293.                    
  294.                     // Convert bytes to a string and put it in the text area
  295.                     if (n == 0) {
  296.                         b = decrypt(1);
  297.                         StringBuilder output = new StringBuilder();
  298.                         ;
  299.                         for (byte bt : b) {
  300.                             output.append((char) bt);
  301.                         }
  302.                         textArea.setText(output.toString());
  303.                     }
  304.                 } else {
  305.                     // The image holds a file
  306.                     Object[] options = { "Save", "Cancel" };
  307.                     int n = JOptionPane.showOptionDialog(frame, "This image contains a file. What would you like to do?", "Message",
  308.                             JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]);
  309.  
  310.                     // Open save dialog and save file to chosen location
  311.                     if (n == 0) {
  312.                         File temp = null;
  313.                        
  314.                         fc.setSelectedFile(new File(new String(b)));
  315.                         int returnVal = fc.showSaveDialog(frame);
  316.  
  317.                         if (returnVal == JFileChooser.APPROVE_OPTION) {
  318.                             temp = fc.getSelectedFile();
  319.                          
  320.                             FileOutputStream fout;
  321.                             try {
  322.                                 fout = new FileOutputStream(temp);
  323.                                 fout.write(decrypt(1));
  324.                                 fout.close();
  325.                             } catch (IOException ex) {
  326.                                 ex.printStackTrace();
  327.                             }
  328.                         }
  329.                     }
  330.                 }
  331.             }
  332.         });
  333.        
  334.         /****************
  335.          * ENCRYPT TEXT *
  336.          ****************/
  337.  
  338.         encryptTextButton.addMouseListener(new MouseAdapter() {
  339.             @Override
  340.             public void mouseClicked(MouseEvent e) {
  341.                 output = deepCopy(key);
  342.                 encrypt("text".getBytes(), 0);
  343.                 encrypt(textToBytes(), 1);
  344.                
  345.                 File f = null;
  346.                 fc.setSelectedFile(new File("result.png"));
  347.                 int returnVal = fc.showSaveDialog(frame);
  348.  
  349.                 if (returnVal == JFileChooser.APPROVE_OPTION) {
  350.                     f = fc.getSelectedFile();
  351.                  
  352.                     try {
  353.                         ImageIO.write(output, "png", f);
  354.                     } catch (Exception ex) {
  355.                         ex.printStackTrace();
  356.                     }
  357.                 }
  358.                 textArea.setText("");
  359.             }
  360.         });
  361.        
  362.         /****************
  363.          * ENCRYPT FILE *
  364.          ****************/
  365.        
  366.         encryptFileButton.addMouseListener(new MouseAdapter() {
  367.             @Override
  368.             public void mouseClicked(MouseEvent e) {
  369.                
  370.                 if (file.length() > (key.getWidth() * key.getHeight()-1) * (3.0/8.0) - 100){
  371.                     JOptionPane.showMessageDialog(frame, "This file to too large. Cannot encrypt", "Warning", JOptionPane.WARNING_MESSAGE);
  372.                     return;
  373.                 }
  374.                
  375.                 System.out.println("got pressed");
  376.                 output = deepCopy(key);
  377.                 encrypt(file.getName().getBytes(), 0);
  378.                 encrypt(fileToBytes(), 1);
  379.  
  380.                 File f = null;
  381.                 fc.setSelectedFile(new File("result.png"));
  382.                 int returnVal = fc.showSaveDialog(frame);
  383.  
  384.                 if (returnVal == JFileChooser.APPROVE_OPTION) {
  385.                     f = fc.getSelectedFile();
  386.                  
  387.                     try {
  388.                         ImageIO.write(output, "png", f);
  389.                     } catch (Exception ex) {
  390.                         ex.printStackTrace();
  391.                     }
  392.                     textArea.setText("");
  393.                 }
  394.             }
  395.         });
  396.        
  397.         /**********
  398.          * LAYOUT * Auto generated by Eclipse WindowBuilder
  399.          **********/
  400.  
  401.         GroupLayout groupLayout = new GroupLayout(frame.getContentPane());
  402.         groupLayout.setHorizontalGroup(
  403.             groupLayout.createParallelGroup(Alignment.LEADING)
  404.                 .addGroup(groupLayout.createSequentialGroup()
  405.                     .addContainerGap()
  406.                     .addGroup(groupLayout.createParallelGroup(Alignment.LEADING, false)
  407.                         .addComponent(codeImageLabel, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
  408.                         .addComponent(loadKeyImageButton, GroupLayout.DEFAULT_SIZE, 177, Short.MAX_VALUE)
  409.                         .addComponent(keyImageLabel, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
  410.                         .addComponent(loadEncodedImageButton, GroupLayout.DEFAULT_SIZE, 177, Short.MAX_VALUE))
  411.                     .addGroup(groupLayout.createParallelGroup(Alignment.TRAILING)
  412.                         .addGroup(groupLayout.createSequentialGroup()
  413.                             .addGap(12)
  414.                             .addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
  415.                                 .addComponent(textArea, GroupLayout.PREFERRED_SIZE, 434, Short.MAX_VALUE)
  416.                                 .addGroup(groupLayout.createSequentialGroup()
  417.                                     .addPreferredGap(ComponentPlacement.RELATED)
  418.                                     .addGroup(groupLayout.createParallelGroup(Alignment.TRAILING)
  419.                                         .addComponent(separator, GroupLayout.DEFAULT_SIZE, 434, Short.MAX_VALUE)
  420.                                         .addGroup(Alignment.LEADING, groupLayout.createSequentialGroup()
  421.                                             .addComponent(fileLabel, GroupLayout.PREFERRED_SIZE, 91, GroupLayout.PREFERRED_SIZE)
  422.                                             .addPreferredGap(ComponentPlacement.RELATED)
  423.                                             .addGroup(groupLayout.createParallelGroup(Alignment.TRAILING)
  424.                                                 .addGroup(groupLayout.createSequentialGroup()
  425.                                                     .addGroup(groupLayout.createParallelGroup(Alignment.LEADING, false)
  426.                                                         .addComponent(btnLoadFile, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
  427.                                                         .addComponent(encryptFileButton, GroupLayout.DEFAULT_SIZE, 115, Short.MAX_VALUE))
  428.                                                     .addGap(224))
  429.                                                 .addComponent(decryptButton)))))))
  430.                         .addGroup(groupLayout.createSequentialGroup()
  431.                             .addPreferredGap(ComponentPlacement.RELATED)
  432.                             .addComponent(encryptTextButton)))
  433.                     .addContainerGap())
  434.         );
  435.         groupLayout.setVerticalGroup(
  436.             groupLayout.createParallelGroup(Alignment.LEADING)
  437.                 .addGroup(groupLayout.createSequentialGroup()
  438.                     .addGap(10)
  439.                     .addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
  440.                         .addGroup(groupLayout.createSequentialGroup()
  441.                             .addComponent(textArea, GroupLayout.DEFAULT_SIZE, 263, Short.MAX_VALUE)
  442.                             .addGap(10)
  443.                             .addComponent(encryptTextButton)
  444.                             .addPreferredGap(ComponentPlacement.RELATED)
  445.                             .addComponent(separator, GroupLayout.PREFERRED_SIZE, 2, GroupLayout.PREFERRED_SIZE)
  446.                             .addPreferredGap(ComponentPlacement.RELATED)
  447.                             .addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
  448.                                 .addGroup(Alignment.TRAILING, groupLayout.createSequentialGroup()
  449.                                     .addGap(3)
  450.                                     .addComponent(fileLabel, GroupLayout.DEFAULT_SIZE, 104, Short.MAX_VALUE))
  451.                                 .addGroup(groupLayout.createSequentialGroup()
  452.                                     .addComponent(btnLoadFile)
  453.                                     .addPreferredGap(ComponentPlacement.RELATED)
  454.                                     .addComponent(encryptFileButton)
  455.                                     .addPreferredGap(ComponentPlacement.RELATED, 33, Short.MAX_VALUE)
  456.                                     .addComponent(decryptButton))))
  457.                         .addGroup(groupLayout.createSequentialGroup()
  458.                             .addGap(1)
  459.                             .addComponent(loadKeyImageButton)
  460.                             .addPreferredGap(ComponentPlacement.RELATED)
  461.                             .addComponent(loadEncodedImageButton)
  462.                             .addPreferredGap(ComponentPlacement.RELATED)
  463.                             .addComponent(keyImageLabel, GroupLayout.PREFERRED_SIZE, 177, GroupLayout.PREFERRED_SIZE)
  464.                             .addPreferredGap(ComponentPlacement.RELATED)
  465.                             .addComponent(codeImageLabel, GroupLayout.PREFERRED_SIZE, 177, GroupLayout.PREFERRED_SIZE)))
  466.                     .addGap(10))
  467.         );
  468.         frame.getContentPane().setLayout(groupLayout);
  469.     }
  470.    
  471.  
  472.     // Returns a byte array for the text or file being encrypted
  473.     private byte[] textToBytes() {
  474.         return textArea.getText().getBytes();
  475.     }
  476.    
  477.     private byte[] fileToBytes() {
  478.         try {
  479.             Path path = Paths.get(file.getAbsolutePath());
  480.             return Files.readAllBytes(path);
  481.         } catch (IOException e) {
  482.             e.printStackTrace();
  483.         }
  484.         return null;
  485.     }
  486.    
  487.     /******************
  488.      * ENCRYPT BINARY * Encodes a byte array into the image starting at pixel row ys
  489.      ******************/
  490.  
  491.     private void encrypt(byte[] bytes, int ys) {
  492.        
  493.         // Builds a literal binary string from the byte array
  494.         StringBuilder binary = new StringBuilder();
  495.         for (byte b : bytes) {
  496.             int val = b;
  497.             for (int i = 0; i < 8; i++) {
  498.                 binary.append((val & 128) == 0 ? 0 : 1);
  499.                 val <<= 1;
  500.             }
  501.         }
  502.  
  503.         // TODO Make this use a boolean array to save memory
  504.         char[] ca = binary.toString().toCharArray();
  505.         int n = 0;
  506.         int rgb;
  507.         outerloop: for (int y = ys; y < output.getHeight(); y++) {
  508.             for (int x = 0; x < output.getWidth(); x++) {
  509.  
  510.                 // For each pixel, get the RGB subpixel values
  511.                 rgb = output.getRGB(x, y);
  512.                 // TODO Implement optional alpha channel
  513.                 int alpha = (rgb >> 24) & 0xFF;
  514.                 int[] c = { (rgb >> 16) & 0xFF, (rgb >> 8) & 0xFF, (rgb) & 0xFF };
  515.  
  516.                 for (int i = 0; i < 3; i++) {
  517.                    
  518.                     // Offset each value by one if bit equals one
  519.                     if (n < binary.length()) {
  520.                         if (ca[n] == '1') {
  521.                             if (c[i] != 255)
  522.                                 c[i]++;
  523.                             else
  524.                                 c[i]--;
  525.                         }
  526.                         n++;
  527.                     } else {
  528.                         // Offset subpixel by two to signify end of bit stream
  529.                         if (c[i] < 254)
  530.                             c[i] += 2;
  531.                         else
  532.                             c[i] -= 2;
  533.                         System.out.println("adding break at " + i + " " + x + " " + y);
  534.                         Color color = new Color(c[0], c[1], c[2], alpha);
  535.                         output.setRGB(x, y, color.getRGB());
  536.  
  537.                         break outerloop;
  538.                     }
  539.                 }
  540.                 Color color = new Color(c[0], c[1], c[2], alpha);
  541.                 output.setRGB(x, y, color.getRGB());
  542.             }
  543.         }
  544.     }
  545.    
  546.     /*****************
  547.      * DECRYPT IMAGE *  Returns a byte array from the image starting at row ys
  548.      *****************/
  549.  
  550.     private byte[] decrypt(int ys) {
  551.         StringBuilder binary = new StringBuilder();
  552.         int rgbc, rgbk;
  553.         outerloop: for (int y = ys; y < key.getHeight(); y++) {
  554.             for (int x = 0; x < key.getWidth(); x++) {
  555.                 // For each subpixel in the current pixel, append the difference between key and code image
  556.                 rgbk = key.getRGB(x, y);
  557.                 rgbc = code.getRGB(x, y);
  558.  
  559.                 int rb = getBinary((rgbk >> 16) & 0xFF, (rgbc >> 16) & 0xFF);
  560.                 int gb = getBinary((rgbk >> 8) & 0xFF, (rgbc >> 8) & 0xFF);
  561.                 int bb = getBinary((rgbk) & 0xFF, (rgbc) & 0xFF);
  562.  
  563.                 int[] b = { rb, gb, bb };
  564.  
  565.                 for (int i = 0; i < 3; i++) {
  566.                     if (b[i] == 2) {
  567.                         break outerloop;
  568.                     } else
  569.                         binary.append(Integer.toString(b[i]));
  570.                 }
  571.             }
  572.         }
  573.        
  574.         // Change string of bits into byte array and return
  575.         byte[] b = new byte[binary.toString().length() / 8];
  576.         int i = 0;
  577.         for (String st : getParts(binary.toString(), 8)) {
  578.             b[i] = (byte) Integer.parseInt(st, 2);
  579.             i++;
  580.         }
  581.  
  582.         return b;
  583.     }
  584.    
  585.     // Returns an integer bit or 2 to signify the end of the bit stream
  586.     private int getBinary(int k, int c) {
  587.         if (Math.abs(k - c) == 1)
  588.             return 1;
  589.         if (Math.abs(k - c) == 0)
  590.             return 0;
  591.         return 2;
  592.     }
  593.  
  594.     // Returns a BufferedImage selected by the user in the Open File Dialog
  595.     private BufferedImage loadImage() {
  596.         int returnVal = fc.showOpenDialog(frame);
  597.         File file;
  598.         BufferedImage image = null;
  599.         if (returnVal == JFileChooser.APPROVE_OPTION) {
  600.             file = fc.getSelectedFile();
  601.             try {
  602.                 image = ImageIO.read(file);
  603.             } catch (IOException e1) {
  604.                 e1.printStackTrace();
  605.             }
  606.         }
  607.         return image;
  608.     }
  609.    
  610.     // Returns an ImageIcon scaled to fit within w by h without altering the aspect ratio
  611.     private ImageIcon getScaledIcon(BufferedImage image, int w, int h) {
  612.  
  613.         int mWidth = w, mHeight = h;
  614.         double scale;
  615.         if (mWidth / image.getWidth() > mHeight / image.getHeight())
  616.             scale = mHeight / (double) image.getHeight();
  617.         else
  618.             scale = mWidth / (double) image.getWidth();
  619.  
  620.         return new ImageIcon(image.getScaledInstance((int) (image.getWidth() * scale), (int) (image.getHeight() * scale), Image.SCALE_FAST));
  621.     }
  622.  
  623.     // Splits the string into units partitionSize long
  624.     private static List<String> getParts(String string, int partitionSize) {
  625.         List<String> parts = new ArrayList<String>();
  626.         int len = string.length();
  627.         for (int i = 0; i < len; i += partitionSize) {
  628.             parts.add(string.substring(i, Math.min(len, i + partitionSize)));
  629.         }
  630.         return parts;
  631.     }
  632.  
  633.     // Returns a separate or 'deep' copy of a BufferedImage
  634.     static BufferedImage deepCopy(BufferedImage bi) {
  635.         ColorModel cm = bi.getColorModel();
  636.         boolean isAlphaPremultiplied = cm.isAlphaPremultiplied();
  637.         WritableRaster raster = bi.copyData(null);
  638.         return new BufferedImage(cm, raster, isAlphaPremultiplied, null);
  639.     }
  640. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement