Javafx displaying image from database.
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
public class PhotoFromDatabase extends Application
{
PreparedStatement ps;
Connection conn;
ResultSet rs;
public static void main(String[]args)
{
Application.launch(args);
}
@Override
public void start(Stage primaryStage)
{
BorderPane bp = new BorderPane();
Scene scene = new Scene(bp,800,600);
ImageView imgView = new ImageView();//setting imageview where we will set our uploaded picture before taking it to the database
imgView.setFitWidth(200);
imgView.setFitHeight(200);
//creating button to help us get our photo from the database
Button loadB = new Button("load");
bp.setBottom(loadB);//placing our load button on the button of our borderpane
bp.setCenter(imgView);//placing our imageview at the center of the borderpane
loadB.setOnAction((ActionEvent t) -> {
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/address","root","kevo");//my database connection string my database name is address username is root and password is kevo
PreparedStatement ps = conn.prepareStatement("SELECT * FROM photos");
rs = ps.executeQuery();
while(rs.next())
{
InputStream is = rs.getBinaryStream("photo");
OutputStream os = new FileOutputStream(new File("photo.jpg"));
byte[]content = new byte[1024];
int size = 0;
while((size=is.read(content))!= -1)
{
os.write(content,0,size);
}
os.close();
is.close();
Image imagex = new Image("file:photo.jpg",250,250,true,true);
imgView.setImage(imagex);
}
conn.close();
} catch (ClassNotFoundException ex) {
Logger.getLogger(PhotoFromDatabase.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(PhotoFromDatabase.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(PhotoFromDatabase.class.getName()).log(Level.SEVERE, null, ex);
}
});
primaryStage.setTitle("Photo From Database To Scene");
primaryStage.setScene(scene);
primaryStage.show();
}
}
The code above gives a result like this:
This comment has been removed by the author.
ReplyDeletehello, i working with MVC logic. I want to get photo from my database. I want to know that what is type of image in javafx? thanks
ReplyDeletePlease Did you find the answer for your question?
Delete