javaimageswingfilejfilechooser

How to store a image and rename that image at the same time while storing?


Want to create a JFileChooser and a JTextFieldThen browse an image from any folder. Path is given, so it will rename the image and the image name would be the jtextfield.getText(); then store in my specified path. I know it's hard to implement. I did some part.

JFileChooser and jtextfield is created. Image is getting stored in my specified path. But it's not renaming the image. (Rename image should be the jtextfield.jpg)

import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.io.File;

public class ImgClass {

    public ImgClass() {
        final JFrame frame = new JFrame("Save Image");

                    final JTextField username = new JTextField();
            username.setBounds(105, 102, 192, 20);
            frame.add(username);
            username.setColumns(10);

        JButton saveImage = new JButton("Browse");
        saveImage.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JFileChooser chooser = new JFileChooser();
                FileNameExtensionFilter filter = new FileNameExtensionFilter(
                        "JPG, GIF, and PNG Images", "jpg", "gif", "png");
                chooser.setFileFilter(filter);
                int returnVal = chooser.showOpenDialog(frame);
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    File file = chooser.getSelectedFile();
                    System.out.println("You choose to open this file: "
                            + file.getName());
                    BufferedImage image;
                    try {
                        image = ImageIO.read(file);
                       ImageIO.write(image, "jpg",new File("D:\\Img\\" + username.getText()+".jpg"));
                    } catch (IOException ex) {
                        Logger.getLogger(ImgClass.class.getName()).log(Level.SEVERE, null, ex);
                    }              
                }
            }
        });



        frame.add(saveImage);
        frame.setLayout(new GridBagLayout());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 300);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);


    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                ImgClass saveImageFile = new ImgClass();
            }
        });
    }
}

Solution

  • You're using the same file name when writing the file. Consider getting the text from the JTextField and using it.

    String newName = username.getText();
    
    // no not this!
    // File newFile = new File("D:\\Img\\" + file.getName()));
    
    // but this!
    file newFile = new File("D:\\Img\\" + newName));
    // write with newFile
    

    Edit
    You state in comment:

    Good approach. But the problem is : If I write ' abc' in jtextfield then image will file format is storing wrong. If I write abc.jpg in jtextfield then it works fine. Please suggest me with any modification.

    I challenge you to write a small bit of code that checks the String (named newName above) to see if it ends in ".jpg" or something similar such as ".JPG" and if not, then provide the String with such an ending. I have confidence that you can solve this. ;)