Results 1 to 14 of 14
Thread: Load and Save images
- 12-23-2010, 04:40 PM #1
Member
- Join Date
- Dec 2010
- Posts
- 20
- Rep Power
- 0
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; }
- 12-23-2010, 04:51 PM #2
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.
- 12-23-2010, 11:55 PM #3
Senior Member
- Join Date
- Jan 2009
- Posts
- 671
- Rep Power
- 5
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.
- 12-24-2010, 10:54 AM #4
Member
- Join Date
- Dec 2010
- Posts
- 20
- Rep Power
- 0
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); } } }
- 12-24-2010, 11:17 AM #5
Member
- Join Date
- Dec 2010
- Posts
- 20
- Rep Power
- 0
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); } }
- 12-26-2010, 05:47 AM #6
Senior Member
- Join Date
- Jan 2009
- Posts
- 671
- Rep Power
- 5
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'?
- 12-26-2010, 09:19 AM #7
Member
- Join Date
- Dec 2010
- Posts
- 20
- Rep Power
- 0
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 }
- 12-26-2010, 04:46 PM #8
Senior Member
- Join Date
- Jan 2009
- Posts
- 671
- Rep Power
- 5
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)?
- 12-26-2010, 07:40 PM #9
Member
- Join Date
- Dec 2010
- Posts
- 20
- Rep Power
- 0
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
- 12-28-2010, 05:28 AM #10
Senior Member
- Join Date
- Jan 2009
- Posts
- 671
- Rep Power
- 5
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);
- 12-28-2010, 09:52 AM #11
Member
- Join Date
- Dec 2010
- Posts
- 20
- Rep Power
- 0
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-28-2010, 10:01 AM #12
Member
- Join Date
- Dec 2010
- Posts
- 20
- Rep Power
- 0
Thanks again for your help. For the previous post, I have been able to solve the problem. The problem was with the line
The BufferedImage.TYPE_INT_ARGB was the problem. It added the alpha component in the color model. The BufferedImage.TYPE_INT_ARGB should beJava Code:BufferedImage bi = new BufferedImage(img.getWidth(null),img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
. Thanks again for your help. I have spent stressful days trying to solve this problem of saving.Java Code:BufferedImage.TYPE_INT_RGB
- 12-29-2010, 04:06 PM #13
Senior Member
- Join Date
- Jan 2009
- Posts
- 671
- Rep Power
- 5
No problem. ...if you have evrything you need, suggest marking the thread as solved.
- 12-29-2010, 06:38 PM #14
Member
- Join Date
- Dec 2010
- Posts
- 20
- Rep Power
- 0
Similar Threads
-
Save/Load ArrayList
By chielt in forum New To JavaReplies: 3Last Post: 05-08-2011, 06:12 PM -
Using JFileChooser to save and load files.
By javapenguin in forum Advanced JavaReplies: 2Last Post: 10-16-2010, 08:24 AM -
Arraylist Save and Load
By frankycool in forum Advanced JavaReplies: 1Last Post: 11-14-2009, 10:29 PM -
save will work but load wont?!?!
By Sticks_ll in forum New To JavaReplies: 1Last Post: 06-12-2008, 04:19 AM -
How to Save/Load Vector to/from file
By Java Tip in forum java.langReplies: 0Last Post: 04-14-2008, 08:37 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks