Saving images using dialogs in java FXML (java 8) - java

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);
}

Related

Java Uploading Image Path To Mysql Missing '/'

I want to upload a path of an image to mysql database but whenever i tried to upload it, it always upload the path without '/'. example i have a file in src/upload/nameofimage.jpg, in the database it's srcuploadnameofimage.jpg
here is the upload button that i have
try {
String newpath = "src/upload";
File directory = new File(newpath);
if (!directory.exists()) {
directory.mkdirs();
}
File fileawal = null;
File fileakhir = null;
String ext = this.filename.substring(filename.lastIndexOf('.')+1);
fileawal = new File(filename);
System.out.println(newpath);
fileakhir = new File(newpath+"/"+Nik.getText()+"."+ext);
System.out.println(fileakhir);
stat = koneksi.createStatement();
stat.executeUpdate("insert into user values ('" + Nik.getText() + "','" + Nama.getText() + "','" + fileakhir.toString() + "')");
System.out.println(fileakhir.toString());
JOptionPane.showMessageDialog(null, "Akun Sudah Terdaftar, Silahkan Kembali Login");
Files.copy(fileawal.toPath(), fileakhir.toPath());
Login log = new Login();
log.setVisible(true);
this.setVisible(false);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
and this is the image picker button that i have
try {
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
File f = chooser.getSelectedFile();
ImageIcon icon = new ImageIcon(f.toString());
Image img = icon.getImage().getScaledInstance(Foto.getWidth(), Foto.getHeight(), Image.SCALE_DEFAULT);
ImageIcon ic = new ImageIcon(img);
Foto.setIcon(ic);
filename = f.getAbsolutePath();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
I have tried using .toString(), .getPath(), .getAbsolutePath(), but none of them include '/' in the database

How can I fix my code so that it contains both a "save" and "save as" functions?

I have two buttons in a menubar that contains both a save and save as button. However, I currently have the code for both of them the same and it does the save as currently with prompting the user where they want to save. I want the save button to only save without prompting for the dialog unless the file doesn't yet exist.
I've tried fiddling around with the code to try and figure out a workaround, but have not figure it out.
fileMenu.getItems().add(saveItem);
saveItem.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
FileChooser saveFile = new FileChooser();
saveFile.getExtensionFilters().add(new FileChooser.ExtensionFilter("Image Files", "*.png", "*.jpg"));
saveFile.setTitle("Save File");
File file = saveFile.showSaveDialog(stage);
if (file != null) {
try {
WritableImage writableImage = new WritableImage(width, height);
canvas.snapshot(null, writableImage);
RenderedImage renderedImage = SwingFXUtils.fromFXImage(writableImage, null);
ImageIO.write(renderedImage, "png", file);
} catch (IOException ex) {
System.out.println("Error");
}
}
}
});
fileMenu.getItems().add(saveAsItem);
saveAsItem.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
FileChooser saveFile = new FileChooser();
saveFile.getExtensionFilters().add(new FileChooser.ExtensionFilter("Image Files", "*.png", "*.jpg"));
saveFile.setTitle("Save File");
File file = saveFile.showSaveDialog(stage);
if (file != null) {
try {
WritableImage writableImage = new WritableImage(width, height);
canvas.snapshot(null, writableImage);
RenderedImage renderedImage = SwingFXUtils.fromFXImage(writableImage, null);
ImageIO.write(renderedImage, "png", file);
} catch (IOException ex) {
System.out.println("Error");
}
}
}
});
The code currently does the exact same save function for each save button. I want it to only prompt for the save as button.
You need to have a File instance field in your class that is initially assigned to null. When you read in a File or when you do your first save, then this field is assigned to that File. When the save button is pressed, then you check if the field is null, and if so, show the dialog as you would for the save-as button. If the field is not null, then you simply write the file to disk using the data that you have and that File.
for example (code not tested):
// a private instance field
private File myFile = null;
fileMenu.getItems().add(saveItem);
saveItem.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
if (myFile == null) {
saveAs();
} else {
writeFile(myFile);
}
}
});
fileMenu.getItems().add(saveAsItem);
saveAsItem.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
saveAs();
}
});
private void writeFile(File file) {
if (file != null) {
try {
WritableImage writableImage = new WritableImage(width, height);
canvas.snapshot(null, writableImage);
RenderedImage renderedImage = SwingFXUtils.fromFXImage(writableImage, null);
ImageIO.write(renderedImage, "png", file);
} catch (IOException ex) {
System.out.println("Error");
}
}
}
private void saveAs() {
FileChooser saveFile = new FileChooser();
saveFile.getExtensionFilters().add(new FileChooser.ExtensionFilter("Image Files", "*.png", "*.jpg"));
saveFile.setTitle("Save File");
File file = saveFile.showSaveDialog(stage);
myFile = file; // !!
writeFile(file);
}

Image didn't load in JPanel

I have a JPanel name "imagePanel" and a button name "browseBtn". All contained in a JFrame class. When pressing the browseBtn, a file chooser will open up and after choosing a PNG image file, the image will appear directly in the imagePanel.
This is the action event for the browseBtn
private void browseBtnActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
JFileChooser fc = new JFileChooser();
int result = fc.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
if (accept(file)) {
try {
ImageIcon image = new ImageIcon(file.getPath());
JLabel l = new JLabel(image);
imagePanel.add(l);
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Error reading file !");
}
}
else {
JOptionPane.showMessageDialog(this, "Choose png file only !");
}
}
}
public boolean accept(File file) {
return file.isDirectory() || file.getAbsolutePath().endsWith(".png");
}
I have choose the correct .png file but i don't understand why the image didn't show up in the imagePanel. Can you guy explain on that ?
Cheers.
You should avoid creating new objects everytime you want to display your image, imagine if you change it 5 times, you're creating 5 times an object while you display only one !
Like said in the comments, your best shot would be to create your label when you create your panel, add it to said panel, then simply change the icon of this label when you load your image.
browseBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser fc = new JFileChooser();
int result = fc.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
if (accept(file)) {
try {
ImageIcon image = new ImageIcon(file.getPath());
label.setIcon(image);
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, "Error reading file !");
}
}
else {
JOptionPane.showMessageDialog(this, "Choose png file only !");
}
}
}
public boolean accept(File file) {
return file.isDirectory() || file.getAbsolutePath().endsWith(".png");
}
});
Assuming label is the reference to said JLabel, created on components initialisation.
Or you might try this :
browseBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser fc = new JFileChooser();
int result = fc.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
if (accept(file)) {
try {
ImageIcon imageIcon = new ImageIcon(new ImageIcon(file.getPath()).getImage().getScaledInstance(20, 20, Image.SCALE_DEFAULT)); //resizing
label.setIcon(imageIcon);
/*try { // or try this
InputStream inStream = this.getClass().getClassLoader().getResourceAsStream(file.getPath());
BufferedImage img = ImageIO.read(inStream);
Image rimg = img.getScaledInstance(width, height, Image.SCALE_STANDARD);
label.setIcon(rimg);
} catch (IOException e) {}*/
} catch (Exception ex) {JOptionPane.showMessageDialog(this, "Error reading file !");}
} else {JOptionPane.showMessageDialog(this, "Choose png file only !");}
}
}
public boolean accept(File file) {
return file.isDirectory() || file.getAbsolutePath().endsWith(".png");
}
});

Append Images to RTF document

I am trying to add images to a rtf document. I am able to add images to the document but I can't append any images. This means that when the 2nd Image is added, the first image is removed. I think that whenever the code is executed a new rtf document is created.
public class InsertToWord {
com.lowagie.text.Document doc = null;
FileOutputStream evidenceDocument;
String fileName = "evidenceDocument.rtf";
settings obj = null;
InsertToWord() {
obj = new settings();
doc = new com.lowagie.text.Document();
}
public void insertImage(File saveLocation) {
try {
evidenceDocument = new FileOutputStream(obj.getFileLocation() + fileName);
RtfWriter2.getInstance(doc, evidenceDocument);
doc.open();
com.lowagie.text.Image image = com.lowagie.text.Image.getInstance(saveLocation.toString());
image.scaleAbsolute(400, 300);
doc.add(image);
doc.close();
} catch (Exception e) {
}
}
}
On your insertImage() method, you are indeed creating a new file and overwriting your old one.
This line is creating the new file:
evidenceDocument = new FileOutputStream(obj.getFileLocation()+fileName);
You can pass the FileOutputStream in as a parameter to the method and then remove the line all together:
public void insertImage( FileOutputStream evidenceDocument , File saveLocation )
This code is the one I´m using to add an image into a RTF format and its working fine :
public void actionPerformed(ActionEvent arg0) {
JFileChooser fileChooser = new JFileChooser();
int option = fileChooser.showOpenDialog(null);
File file = fileChooser.getSelectedFile();
if (option == JFileChooser.APPROVE_OPTION) {
try {
BufferedImage image = ImageIO.read(file);
image = Scalr.resize(image, 200);
document = (StyledDocument) textPane.getDocument();
javax.swing.text.Style style = document.addStyle("StyleName", null);
StyleConstants.setIcon(style, new ImageIcon(image));
document.insertString(document.getLength(), "ignored text", style);
}
catch (Exception e) {
e.printStackTrace();
}
}
if (option == JFileChooser.CANCEL_OPTION) {
fileChooser.setVisible(false);
}
}// End of Method
The textPane variable is a JTextPane.

How to save Icon object into a file via JFileChooser?

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.

Categories