-1

In my class, the attribute where the image will be saved is defined like this:

    @Lob
    @Column(name = "NOTA_FISCAL", nullable = false, columnDefinition = "mediumblob")
    public byte[] getNOTA_FISCAL() {
        return NOTA_FISCAL;
    }

    public void setNOTA_FISCAL(byte[] NOTA_FISCAL) {
        this.NOTA_FISCAL = NOTA_FISCAL;
    }

In a project I made using Swing, I used JFileChooser to read an image from my computer to later insert it into the database, we can see that the file is converted to Bytes before inserting the item.

private void selecionarNF(ActionEvent event) {
        JFileChooser fc = new JFileChooser();
        int res = fc.showOpenDialog(null);

        if (res == JFileChooser.APPROVE_OPTION) {
            File arquivo = fc.getSelectedFile();
            System.out.println("Arquivo: " + arquivo + "");
            textCaminhoNF.setText(String.valueOf(arquivo));
            try {
                byte[] fotonf = new byte[(int) arquivo.length()];
                FileInputStream fileInputfotonf = new FileInputStream(arquivo);
                fileInputfotonf.read(fotonf);
                fileInputfotonf.close();
                fotoNF = fotonf;
            } catch (Exception ex) {
                // System.out.println(ex.printStackTrace().toString());
            }
        } else {
            JOptionPane.showMessageDialog(null, "Você nao selecionou nenhum arquivo.");
        }

I'm implementing it with JavaFX, I could even continue using Swing, but I intend to use the Windows file explorer, this way using FileChooser, however I'm having problems capturing the image and passing it to an object of type File, the . getSelectedFile() doesn't exist for FileChooser, I searched a lot on the internet and couldn't find a way to capture this file. What would be the correct way?

        Stage s = new Stage();        
        FileChooser fc = new FileChooser();        
        textCaminhoNF.setText(fc.showOpenDialog(s).getAbsolutePath());       
        
        File arquivo = fc.getSelectedFile(); //his line shows the error, because there is no .getSelectItem
        
        if (fc != null) {            
            System.out.println("No is null");    
            try
            {
                byte[] fotonf = new byte[(int) fc.length()];
                FileInputStream fileInputfotonf = new FileInputStream(fc);
                fileInputfotonf.read(fotonf);
                fileInputfotonf.close();
                fotoNF = fotonf;
            } catch (Exception ex) {
                // System.out.println(ex.printStackTrace().toString());
            }
        } 
Homer
  • 17
  • 3
  • 1
    You have `textCaminhoNF.setText(fc.showOpenDialog(s).getAbsolutePath());`. That's setting the text (of a label?) to the selected file's path. That means you have gotten the file. The problem is you don't store it in a variable, so you lose all references to it. There is no property of `FileChooser` that lets you get the previously selected file. You'll have to do something like `File file = fc.showOpenDialog(s);` and then use `file` as needed (checking that it's not `null`, which your current code does not do; i.e., the `textCaminhoNF.setText(...)` line is vulnerable to an NPE). – Slaw Aug 09 '22 at 21:58

2 Answers2

3

I agree with what @slaw has mentioned. You are not saving the file reference returned from showOpenDialog.

Below is a quick demo [from my archives ;-) ] when I tried to check the behavior of FileChooser:

import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class ChooseImage_Demo extends Application {

    ImageView myImageView;

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {
        Button button = new Button("Search for Image");
        button.setOnAction(e -> {
            FileChooser fileChooser = new FileChooser();
            File file = fileChooser.showOpenDialog(null);
            try {
                BufferedImage bufferedImage = ImageIO.read(file);
                Image image = SwingFXUtils.toFXImage(bufferedImage, null);
                myImageView.setImage(image);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        });

        myImageView = new ImageView();
        myImageView.setFitWidth(500);
        myImageView.setPreserveRatio(true);

        VBox vBox = new VBox(10);
        vBox.getChildren().addAll(button, myImageView);
        vBox.setAlignment(Pos.TOP_CENTER);
        Scene scene = new Scene(vBox, 800, 800);
        primaryStage.setTitle("Image Chooser");
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}
Sai Dandem
  • 8,229
  • 11
  • 26
  • 1
    No need to read the file into a buffered image and convert it into an FXImage. A JavaFX Image constructor can read the file directly once it is converted to a URL or stream (assuming the image is stored in a compatible format). – jewelsea Aug 10 '22 at 08:55
  • @jewelsea Thanks for tip :). Yeah the following code is working `Image image = new Image(file.toURI().toURL().toExternalForm());` Did'nt noticed this constructor. – Sai Dandem Aug 10 '22 at 23:35
  • java naming conventions please;) – kleopatra Aug 11 '22 at 06:01
0

Thanks for the help, I did it this way and it worked, it's writing correctly to the database too.

@FXML
private void selecionarNF(ActionEvent event) {

    ImageView myImageView = null;
    myImageView = new ImageView();
    FileChooser fileChooser = new FileChooser();
    File file = fileChooser.showOpenDialog(null);
    try {
        BufferedImage bufferedImage = ImageIO.read(file);
        Image image = SwingFXUtils.toFXImage(bufferedImage, null);
        myImageView.setImage(image);
        imageToByte(String.valueOf(file));
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    textCaminhoNF.setText(String.valueOf(file));
}
Homer
  • 17
  • 3