Results 1 to 14 of 14
  1. #1
    shakeel is offline Member
    Join Date
    Dec 2010
    Posts
    20
    Rep Power
    0

    Default Load and Save images

    Hi, I'm currently doing a project and I'm having some problems with load and save images. My image manipulation part works fine. Here are my codes for loading an image. The only problem that I'm having is how to save that image I've loaded and modified. How can the saving be done?

    LOAD IMAGE
    XML Code:
    private void menuLoadActionPerformed(java.awt.event.ActionEvent evt) {                                         
            JFileChooser loadChooser = new JFileChooser();
            loadChooser.setCurrentDirectory(new File("."));
            String[] extensions = ImageIO.getReaderFileSuffixes();
            
            String[] jpegExtensions = {"jpg", "jpeg", "jpe", "jfif"};
    
            loadChooser.setFileFilter(new FileNameExtensionFilter("JPEG Files(*.jpg, *.jpeg, *.jpe, *.jfif)", jpegExtensions));
            loadChooser.setFileFilter(new FileNameExtensionFilter("GIF Files(*.gif)", "gif"));
            loadChooser.setFileFilter(new FileNameExtensionFilter("PNG Files(*.png)", "png"));
            loadChooser.setFileFilter(new FileNameExtensionFilter("Image files", extensions));
            
            
         
           
            if (loadChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
                ImageFrame frame = new ImageFrame();
                frame.setBounds(0, 70, 400, 400);
                String filename = loadChooser.getSelectedFile().getAbsolutePath();
                
                String nonAuthorisedExtension = getExtension(filename);
                
                if(nonAuthorisedExtension.equals("bmp")){
                    JOptionPane.showMessageDialog(this, "Bitmap files not supported", "NOT SUPPORTED", JOptionPane.INFORMATION_MESSAGE);
                    return;
                }
                else{
                    frame.loadImage(filename);
                    frame.setTitle(filename);
                    displayPane.add(frame);
                    frame.setVisible(true);
                }
                
        }
        }          
    
    public String getExtension(String filename){
            String fname="";
            String ext="";
            int mid= filename.lastIndexOf(".");
            fname=filename.substring(0,mid);
            ext=filename.substring(mid+1,filename.length());
            System.out.println("File Path ="+fname);
            System.out.println("Extension ="+ext);
            return ext;
        }

  2. #2
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    3,702
    Rep Power
    8

    Default

    What have you tried?

    Read this: Lesson: Basic I/O (The Java™ Tutorials > Essential Classes)

    If you post code, it should be in the form of an SSCCE.

  3. #3
    toadaly is offline Senior Member
    Join Date
    Jan 2009
    Posts
    671
    Rep Power
    6

    Default

    To save the file, use a JFileChooser again, but call "showSaveDialog" instead of "showOpenDialog". Then use ImageIO.write to perform the correct type transformation and physically save the file.

  4. #4
    shakeel is offline Member
    Join Date
    Dec 2010
    Posts
    20
    Rep Power
    0

    Default

    I have done the .showSaveDialog part. My problem is with the ImageIO.write. Here is my code for save

    Java Code:
    private void menuSaveActionPerformed(java.awt.event.ActionEvent evt) {
            JFileChooser saveChooser = new JFileChooser();
            saveChooser.setFileFilter(new FileNameExtensionFilter("JPEG File", "jpg"));
            saveChooser.setFileFilter(new FileNameExtensionFilter("PNG File", "png"));
            saveChooser.setFileFilter(new FileNameExtensionFilter("GIF File", "gif"));
            if(saveChooser.showSaveDialog(this)==JFileChooser.APPROVE_OPTION){
                String name = saveChooser.getSelectedFile().getAbsolutePath();
                String name1 = saveChooser.getFileFilter().getDescription();
                if (name1.equals("JPEG File")){
                    String ext = ".jpg";
                    name = name + ext;
                    System.out.println(name);
                }
                else if(name1.equals("PNG File")){
                    String ext = ".png";
                    name = name + ext;
                    System.out.println(name);
                }
                else if(name1.equals("GIF File")){
                    String ext = ".gif";
                    name = name + ext;
                    System.out.println(name);
                }
                else if(name1.equals("All Files")){
                    
                    System.out.println(name);
                }
                else{
                    JOptionPane.showMessageDialog(this, "Error in saving file", "ERROR", JOptionPane.ERROR_MESSAGE);
                }
                try {
                    ImageIO.write((RenderedImage) frame.getImage(), "png", File.createTempFile(name, name1));
                } catch (IOException ex) {
                    Logger.getLogger(WarpingFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }

  5. #5
    shakeel is offline Member
    Join Date
    Dec 2010
    Posts
    20
    Rep Power
    0

    Default

    The fact is that when loading, I'm using JinternalFrame and a label to store the image and as such, im using ImageIcon. ImageIO.write is for BufferedImages and I have to cast RenderedImage to my image file when saving. Is there any other way to save ImageIcon other than ImageIO.write?? Here is my loading code in addition to the one I have given above:
    Java Code:
     public void loadImage(String imageName){
            
            try {
                lblShowImage.setIcon(new ImageIcon(imageName));
                myImage = SimpleFilter.copyImage(((ImageIcon) lblShowImage.getIcon()).getImage());
                currentImage = SimpleFilter.copyImage(myImage);
                if (myImage == null){
                    JOptionPane.showMessageDialog(this,"NOT SUPPORTED");
                    return;
                }
            } catch (InterruptedException ex) {
                JOptionPane.showMessageDialog(this, "An error occured during Loading", "LOAD ERROR", JOptionPane.ERROR_MESSAGE);
            }
            catch (OutOfMemoryError e) {
                JOptionPane.showMessageDialog(this, "Image too Large." , "LARGE IMAGE", JOptionPane.ERROR_MESSAGE);
             
            }
            
        }

  6. #6
    toadaly is offline Senior Member
    Join Date
    Jan 2009
    Posts
    671
    Rep Power
    6

    Default

    I don't see anything wrong with the ImageIO.write code. My guess is that the problem is related to 'getImage'. What class is 'frame'?

  7. #7
    shakeel is offline Member
    Join Date
    Dec 2010
    Posts
    20
    Rep Power
    0

    Default

    Frame is an instance of a class I created. The codes for this class is:

    Java Code:
    package assignment;
    
    import java.awt.*;
    import javax.swing.*;
    import java.util.*;
    import img.*;
    
    
    /**
     *
     *  @author shak
     */
    public class ImageFrame extends javax.swing.JInternalFrame {
    
        private Image myImage;
        private Image currentImage;
    
        private ArrayList<Filter> filterList = new ArrayList<Filter>();
        
        /** Creates new form ImageFrame */
        public ImageFrame() {
            initComponents();
        }
        
        public Image getImage() {
            return currentImage;
        }
        
        public void loadImage(String imageName){
            
            try {
                ImageIcon img = new ImageIcon(imageName);
                lblDisplay.setIcon(img);
                myImage = ((ImageIcon)lblDisplay.getIcon()).getImage();
                currentImage = myImage;
                //myImage = SimpleFilter.copyImage(((ImageIcon) lblDisplay.getIcon()).getImage());
               // currentImage = SimpleFilter.copyImage(myImage);
                if (myImage == null){
                    JOptionPane.showMessageDialog(this,"NOT SUPPORTED");
                    return;
                }
            }
            //catch (InterruptedException ex) {
            catch (Exception ex) {
                JOptionPane.showMessageDialog(this, "An error occured during Loading", "LOAD ERROR", JOptionPane.ERROR_MESSAGE);
            }
            catch (OutOfMemoryError e) {
                JOptionPane.showMessageDialog(this, "Image too Large." , "LARGE IMAGE", JOptionPane.ERROR_MESSAGE);
               /** if (answer == JOptionPane.YES_OPTION){
    
                }*/
            }
            
        }
        
        public void preview(Image img) {
            lblDisplay.setIcon(new ImageIcon(img));
        }
        
        protected void refreshFilters() {
    
            System.out.println("All filters flushed");
            try {
                currentImage = SimpleFilter.copyImage(myImage);
                for (Filter f : filterList) {
                    long timeStart = (new Date()).getTime();
                    currentImage = f.apply(currentImage);
                    long timeStop = (new Date()).getTime();
                    System.out.println(f + " filter applied (" + (timeStop - timeStart) + " ms.)");
                }
            } catch (InterruptedException ex) {
                JOptionPane.showMessageDialog(this, ex.getMessage());
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this, e);
            }
            lblDisplay.setIcon(new ImageIcon(currentImage));
        }
        
        protected void refreshCombo() {
            cbxFilter.removeAllItems();
            for (Filter f : filterList) {
                cbxFilter.addItem(f);
            }
            cbxFilter.setSelectedIndex(cbxFilter.getItemCount() - 1);
        }
        
        public void save(Filter f) {
            filterList.add(f);
            System.out.println("Filter " + f + " added");
            refreshCombo();
            refreshFilters();
        }
    
       public void reset() {
            lblDisplay.setIcon(new ImageIcon(currentImage));
        }
        
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
         */
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
    
            jScrollPane1 = new javax.swing.JScrollPane();
            lblDisplay = new javax.swing.JLabel();
            cbxFilter = new javax.swing.JComboBox();
            btnUndo = new javax.swing.JButton();
    
            setClosable(true);
            setIconifiable(true);
            setMaximizable(true);
            setResizable(true);
            addPropertyChangeListener(new java.beans.PropertyChangeListener() {
                public void propertyChange(java.beans.PropertyChangeEvent evt) {
                    formPropertyChange(evt);
                }
            });
    
            lblDisplay.setForeground(new java.awt.Color(255, 255, 255));
            jScrollPane1.setViewportView(lblDisplay);
    
            btnUndo.setText("Undo");
            btnUndo.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    btnUndoActionPerformed(evt);
                }
            });
    
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(cbxFilter, javax.swing.GroupLayout.PREFERRED_SIZE, 229, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(btnUndo)
                    .addContainerGap(109, Short.MAX_VALUE))
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 401, Short.MAX_VALUE)
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(cbxFilter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(btnUndo))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 265, Short.MAX_VALUE))
            );
    
            pack();
        }// </editor-fold>
    
    private void formPropertyChange(java.beans.PropertyChangeEvent evt) {                                    
    // TODO add your handling code here:
    }                                   
    
    private void btnUndoActionPerformed(java.awt.event.ActionEvent evt) {                                        
        try {
            filterList.remove(cbxFilter.getSelectedIndex());
            refreshCombo();
            refreshFilters();
        }
        catch (ArrayIndexOutOfBoundsException e) {
            JOptionPane.showMessageDialog(this, "Nothing to undo", "CANNOT UNDO", JOptionPane.INFORMATION_MESSAGE);
        }
    }                                       
    
    
        // Variables declaration - do not modify
        private javax.swing.JButton btnUndo;
        private javax.swing.JComboBox cbxFilter;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JLabel lblDisplay;
        // End of variables declaration
    
      
    
    }

  8. #8
    toadaly is offline Senior Member
    Join Date
    Jan 2009
    Posts
    671
    Rep Power
    6

    Default

    My suspicion is that the images being returned by one or more of your filters are volatile.

    Does the ImageIO.write call throw an exception, or is the image it saves just not what you expect (or does it just do nothing without complaining)?

  9. #9
    shakeel is offline Member
    Join Date
    Dec 2010
    Posts
    20
    Rep Power
    0

    Default

    As a matter of fact, it does complain a lot. The error I get is:
    Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: sun.awt.image.ToolkitImage cannot be cast to java.awt.image.BufferedImage

  10. #10
    toadaly is offline Senior Member
    Join Date
    Jan 2009
    Posts
    671
    Rep Power
    6

    Default

    Ok, well that's the issue then. ImageIO.write only works with rendered images.

    You can create a BufferedImage from other toolkit images, and then write BufferedImage.

    pseudo code...

    Java Code:
    BufferedImage newImage = new BufferedImage(width, height, imageType);
    
    Graphics g = newImage.getGraphics();
    
    g.drawImage(oldImage,0,0,null);
    
    g.dispose();
    
    ImageIO.write(newImage, fileType);

  11. #11
    shakeel is offline Member
    Join Date
    Dec 2010
    Posts
    20
    Rep Power
    0

    Default

    Thank you for your help. It worked, that is the image was saved on the PC but there is only one problem. The saved image is abnormally coloured, even if I have not done any image manipulation on it (Just load and save, image is different). Do you have any idea as to why its like that???

    My modified code is like that:
    Java Code:
    if(saveChooser.showSaveDialog(this)==JFileChooser.APPROVE_OPTION){
                String name = saveChooser.getSelectedFile().getAbsolutePath();
                String name1 = saveChooser.getFileFilter().getDescription();
                //File file = new File(saveChooser.getSelectedFile());
    
               
                if (name1.equals("JPEG File")){
                    String ext = ".jpg";
                    name = name + ext;
                    System.out.println(name);
                    try {
                        File file = new File(name);
                        Image img = frame.getImage();
                        BufferedImage bi = new BufferedImage(img.getWidth(null),img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
                        Graphics g = bi.getGraphics();
                        g.drawImage(img,0, 0,null);
                        g.dispose();
                        ImageIO.write(bi,"jpeg", file);
                        
                    } catch (Exception ex) {
                        System.out.println(ex);
                        JOptionPane.showMessageDialog(this, ex);
                    }
                }

  12. #12
    shakeel is offline Member
    Join Date
    Dec 2010
    Posts
    20
    Rep Power
    0

    Default

    Thanks again for your help. For the previous post, I have been able to solve the problem. The problem was with the line
    Java Code:
    BufferedImage bi = new BufferedImage(img.getWidth(null),img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
    The BufferedImage.TYPE_INT_ARGB was the problem. It added the alpha component in the color model. The BufferedImage.TYPE_INT_ARGB should be
    Java Code:
    BufferedImage.TYPE_INT_RGB
    . Thanks again for your help. I have spent stressful days trying to solve this problem of saving.

  13. #13
    toadaly is offline Senior Member
    Join Date
    Jan 2009
    Posts
    671
    Rep Power
    6

    Default

    No problem. ...if you have evrything you need, suggest marking the thread as solved.

  14. #14
    shakeel is offline Member
    Join Date
    Dec 2010
    Posts
    20
    Rep Power
    0

Similar Threads

  1. Save/Load ArrayList
    By chielt in forum New To Java
    Replies: 3
    Last Post: 05-08-2011, 06:12 PM
  2. Using JFileChooser to save and load files.
    By javapenguin in forum Advanced Java
    Replies: 2
    Last Post: 10-16-2010, 08:24 AM
  3. Arraylist Save and Load
    By frankycool in forum Advanced Java
    Replies: 1
    Last Post: 11-14-2009, 10:29 PM
  4. save will work but load wont?!?!
    By Sticks_ll in forum New To Java
    Replies: 1
    Last Post: 06-12-2008, 04:19 AM
  5. How to Save/Load Vector to/from file
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-14-2008, 08:37 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •