display bytes from database as image in imageview in javafx


Question

please I have been stuck on how to convert my stored images from my database and display it as an image in imageview in javafx.

All the previously asked questions have not helped me. I'm using objectdb as my database I also used fxml to build my GUI

for (Person p : person) {
            name.setText(p.getName());
            gender.setText(p.getGender());

            byte[] byteArray = p.getImage();
            image.setImage(new Image(new ByteArrayInputStream(byteArray)));

}
1
0
7/28/2017 8:35:21 AM

I'll show a detailed step on saving to the database using a file chooser and writing an image to a file in a directory(folder) on your hard drive, and also displaying it to imageview in fmxl GUI.

The following below are triggered during a button event or initialized from the controller

FileChooser choose = new FileChooser();
FileChooser.ExtensionFilter extFilterJPG = new FileChooser.ExtensionFilter("JPG files (*.jpg)", "*.JPG");
        FileChooser.ExtensionFilter extFilterPNG = new FileChooser.ExtensionFilter("PNG files (*.png)", "*.PNG");
        choose.getExtensionFilters().addAll(extFilterJPG, extFilterPNG);
File file = choose.showOpenDialog(null);
        try {
            BufferedImage bufferedImage = ImageIO.read(file);
            byte[] b;
            try (ByteArrayOutputStream out = new ByteArrayOutputStream(262144)) {
                ImageIO.write(bufferedImage, "jpg", out);
                out.flush();
                b = out.toByteArray();
            }
EntityService service = new EntityService();
Person p = new Person();
            p.setId(UUID.randomUUID().toString());
            p.setImage(b);
            service.putPerson(p);
} catch (IOException e) {
            e.printStackTrace();
        }




Person p = service.getPerson();
        byte[] byteArray = p.getImage();
        ByteArrayInputStream in = new ByteArrayInputStream(byteArray);
        BufferedImage read = ImageIO.read(in);
        image.setImage(SwingFXUtils.toFXImage(read, null));


String output = "C:\\java\\images\\1.jpg";
        try (FileOutputStream fos = new FileOutputStream(output)) {
            fos.write(byteArray);
        } catch (FileNotFoundException ex) {
            System.out.println("FileNotFoundException : " + ex);
        } catch (IOException ioe) {
            System.out.println("IOException : " + ioe);
        }
2
7/28/2017 9:48:40 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon