How to save Icon object into a file via JFileChooser? - java

I have a JLabel inside which I have saved my ImageIcon like this:
ImageIcon imageIcon = sample.map(); // a map method create an ImageIcon object
imageLabel.setIcon(imageIcon);
imageLabel.setVisible(true);
Now I would like to save this ImageIcon object into a PNG file when clicking on the Save item menu.
private void imageActionPerformed(java.awt.event.ActionEvent evt) {
Icon pic = imageLabel.getIcon();
JFileChooser fileChooser = new JFileChooser("C:/");
fileChooser.setSelectedFile(file);
// this filter will allow just PNG extension
FileFilter filter = new MyCustomFilter2();
fileChooser.setFileFilter(filter);
int returnVal = fileChooser.showSaveDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION)
{
File fileToSave = fileChooser.getSelectedFile();
}
else
{
System.out.println("File access cancelled by user.");
}
}
Yes I know that this code is wrong and some part is missing, I think I should somehow save my Icon object called pic into a File object. This is my assumption. How can I do it please?
Thanks for any help,
Michal.
Here is my source code
private void imageActionPerformed(java.awt.event.ActionEvent evt) {
try{
Icon image = imageLabel.getIcon();
BufferedImage bi = new BufferedImage(image.getIconWidth(),image.getIconHeight(),BufferedImage.TYPE_INT_RGB);
Graphics g = bi.createGraphics();
File file = new File("outputFile");
JFileChooser fileChooser = new JFileChooser("C:/");
fileChooser.setSelectedFile(file);
FileFilter filter = new MyCustomFilter2();
fileChooser.setFileFilter(filter);
int returnVal = fileChooser.showSaveDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION)
{
ImageIO.write(bi, "PNG", file);
File fileToSave = fileChooser.getSelectedFile();
}
else
{
System.out.println("File access cancelled by user.");
}
}
catch(IOException e){
e.printStackTrace();
}
}

The File object returned by the JFileChooser just represents the location on disk where the user would like to save the file. After that you'll want to use ImageIO.write() to save the file to disk.
e.g.
ImageIO.write(image, "png", file);
If you have an Icon, I think you may need to convert that to a BufferedImage before you can save it.

Related

Saving images using dialogs in java FXML (java 8)

So im trying to save a image (Image class from javafx.scene.image.Image) onto a file with a save file dialog (JFileChooser) so that it is user friendly.
What i want it to do: Save the image specified
What it does: Save dialog works (i think), and it doesn't save (write to file) anything.
Here is the code behind it:
public void saveFile() { //menu item interface for save and save as
JFrame parentFrame = new JFrame();
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("Save");
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
//Setting the file extentions
/*fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("PNG Image", ".png"));
fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("JPG Image", ".jpg"));
fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("BMP Image", ".bmp"));*/
int userSelection = fileChooser.showSaveDialog(parentFrame);
if (userSelection == JFileChooser.APPROVE_OPTION) {
File fileToSave = fileChooser.getSelectedFile(); //selected file
saveToFile(picFrame.getImage(), fileToSave); //save the file
System.out.println("Save as file: " + fileToSave.getAbsolutePath()); //debug because it doesnt work
}
parentFrame.dispose();
}
and here is saveToFile
public static void saveToFile(Image image, File file) {
String extension = "";
File outputFile = file;
try {
if (file != null && file.exists()) {
String name = file.getName();
extension = name.substring(name.lastIndexOf("."));
}
} catch (Exception e) {
extension = "";
}
BufferedImage bImage = SwingFXUtils.fromFXImage(image, null);
try {
ImageIO.write(bImage, extension, outputFile);
System.out.println("Saveing file");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
After some digging arround and debuging i found the problem and the solution , so here it is.
All the code.
public void saveFile() { //menu item interface for save and save as
Window mainStage = ap.getScene().getWindow(); //get ze window
FileChooser fileChooser = new FileChooser(); //Filechooser the class that has the file chooser
fileChooser.setTitle("Open Resource File"); //Title of prompt
fileChooser.getExtensionFilters().addAll( //add filter
new ExtensionFilter("Image Files", "*.png", "*.jpg", "*.gif", ".bmp"), //Filters
new ExtensionFilter("All Files", "*.*")); //Filters
File selectedFile = fileChooser.showSaveDialog(mainStage); //get the file
if (selectedFile != null) { //if something is selected then
System.out.println(selectedFile.getAbsoluteFile()); //debug
System.out.println(selectedFile.getAbsoluteFile().getParent()); //debug
Image img = SwingFXUtils.toFXImage(bImg, null); //convert to Image
saveToFile(img, selectedFile); //save the Image
}
}
/**
* A simple image save
*
* #param image The image you want to save
* #param file The file where you want to save it
*/
public static void saveToFile(Image image, File file) {
File outputFile = file; //file
BufferedImage bImage = SwingFXUtils.fromFXImage(image, null); //Convert to bufferedimage
try {
ImageIO.write(bImage, getFileExtension(outputFile).toUpperCase(), outputFile.getAbsoluteFile()); //actualy save
System.out.println("Saveing file ex: " + getFileExtension(outputFile).toUpperCase() + " to: " + outputFile.getAbsoluteFile() + " with name " + outputFile.getName());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static String getFileExtension(File file) {
String name = file.getName();
int lastIndexOf = name.lastIndexOf(".") + 1;
if (lastIndexOf == -1) {
return ""; // empty extension
}
return name.substring(lastIndexOf);
}

Can't load Image into JTextArea using Swing

I am using JFileChooser to load image from the desktop into JTextArea but when I load image from PC, the software hangs.
Here is the code of OpenActionPerformed method of the file chooser.
private void OpenActionPerformed(java.awt.event.ActionEvent evt) {
int returnVal = fileChooser.showOpenDialog(this);
if (returnVal == fileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
try {
// What to do with the file, e.g. display it in a TextArea
textarea.read( new FileReader( file.getAbsolutePath() ), null );
} catch (IOException ex) {
System.out.println("problem accessing file"+file.getAbsolutePath());
}
} else {
System.out.println("File access cancelled by user.");
}
A JTextArea is for text not for images.
If you want to display an image then add an ImageIcon to a JLabel and add the label to the JFrame.
Read the section from the Swing tutorial on How to Use Icons for more information on reading images and displaying Icons.

how to properly save a picture path in a database and assign it into a button?

How can I know the path of the picture that will be store in this button. Also, what type of picture will you recommend me to upload in this button ?
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JFileChooser fc = new JFileChooser();
int result = fc.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
try {
File file = fc.getSelectedFile();
btnNewButton.setIcon(new ImageIcon(ImageIO.read(file)));
} catch (IOException e) {
JOptionPane.showMessageDialog(null, e);
}
}
}
});
how can i know the path of the picture that will be store in this
button
This can be easily done by calling File.getPath() method:
File file = fc.getSelectedFile();
System.out.println(file.getPath());
Additionaly you can store this path in the button through JComponent.putClientProperty(Object key, Object value):
File file = fc.getSelectedFile();
btnNewButton.putClientProperty("imagepath", file.getPath());
what type of picture will you recommend me to upload in this button ?
It can be JPG, PNG, BMP, WBMP and GIF, as per javax.imageio package description. Be aware Java doesn't support ICO format natively: Adding image to JButton

How to restrict file choosers in java to specific files?

private void openMenuActionPerformed(java.awt.event.ActionEvent evt) {
DBmanager db = new DBmanager();
if (!db.getCurrentUser().equals("Admin")) {
JOptionPane.showMessageDialog(this, "You are Not Allowed to Run Applications");
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("PDF Documents", "pdf"));
fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("MS Office Documents", "docx", "xlsx", "pptx"));
fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("Images", "jpg", "png", "gif", "bmp"));
fileChooser.setAcceptAllFileFilterUsed(false);
int returnVal = fileChooser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
if (Desktop.isDesktopSupported()) {
try {
Desktop.getDesktop().open(file);
} catch (Exception e) {
e.printStackTrace();
}
}
}
} else if (db.getCurrentUser().equals("Admin")) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setAcceptAllFileFilterUsed(true);
int returnVal = fileChooser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
if (Desktop.isDesktopSupported()) {
try {
Desktop.getDesktop().open(file);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}// TODO add your handling code here:
}
I am trying to filter files in a file filter by setting fileChooser.setAcceptAllFileFilterUsed(false);. The "all files" option disappears from the FileChooser but all files remain visible unless you select an option from PDF documents,ms Office or images. I want to have only my 3 custom filters upon opening the file chooser.
For example, if you want to filter your JFileChooser to strictly display most commonly found image files, you would use something like this:
FileNameExtensionFilter filter = new FileNameExtensionFilter("Image Files", "jpg", "png", "gif", "jpeg");
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(filter);
The first argument is the description (what gets displayed upon selection at the bottom) and the second argument are the informal file extensions.
You can use FileNameExtensionFilter to add allowed extensions to your FileChooser dialog. Here's an example:
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"JPG & GIF Images", "jpg", "gif");
chooser.setFileFilter(filter);
For more info, please refer to the Javadocs: FileNameExtensionFilter
In my case, I had to put the
setFileFilter(
new FileNameExtensionFilter("Default file filter", ...)
);
after all other calls to the method
addChoosableFileFilter(...);
to make setAcceptAllFileFilterUsed(false) works.
This works fine in java8.1
JFileChooser dbfilechooser = new JFileChooser();
FileNameExtensionFilter filter1 =
new FileNameExtensionFilter("xls","xls");
FileNameExtensionFilter filter2 =
new FileNameExtensionFilter("xlsx", "xlsx");
FileNameExtensionFilter filter3 =
new FileNameExtensionFilter("csv", "csv");
dbfilechooser.addChoosableFileFilter(filter1);
dbfilechooser.addChoosableFileFilter(filter2);
dbfilechooser.addChoosableFileFilter(filter3);

how to upload and display image in JFrame using JFileChooser

I need to upload and display an image selected with the JFileChooser (i.e the user wants to set his/her profile picture) in a JFrame.. How should I do it?
Here is my code for choosing the file:
private void UploadImageActionPerformed(java.awt.event.ActionEvent evt) {
int returnVal = fileChosser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fileChosser.getSelectedFile();
// What to do with the file
// I want code for this part
try {
//code that might create an exception
}
catch (Exception e1) {
e.printStackTrace();
}
}
}
I solved it myself. I chose an image and displayed in a JLabel.
Here is My code:
private void uploadImageActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser filechooser = new JFileChooser();
filechooser.setDialogTitle("Choose Your File");
filechooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
// below code selects the file
int returnval = filechooser.showOpenDialog(this);
if (returnval == JFileChooser.APPROVE_OPTION)
{
File file = filechooser.getSelectedFile();
BufferedImage bi;
try {
// display the image in a Jlabel
bi = ImageIO.read(file);
jLabel1.setIcon(new ImageIcon(bi));
} catch(IOException e) {
e.printStackTrace(); // todo: implement proper error handeling
}
this.pack();
}
}

Categories