Skip to content

Instantly share code, notes, and snippets.

@alamenai
Created December 28, 2017 09:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alamenai/c9d171364318c084d91d0fa51176f4f9 to your computer and use it in GitHub Desktop.
Save alamenai/c9d171364318c084d91d0fa51176f4f9 to your computer and use it in GitHub Desktop.
Read an image from database
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package readimage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javafx.scene.image.Image;
/**
*
* @author Electron
*/
public class ReadImage {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
}
public Image getImage(String Id) throws FileNotFoundException, IOException, SQLException {
FileOutputStream fos = null; //Path of our Image
File imageFile = null;
Image userImage = null;
try {
//------------------------------------------------------------------------------
String queryInsertEmployer = "SElECT image FROM users WHERE id_user=" + "'" + Id + "'";//Select query
//--------------------------------------------------------------------------------
PreparedStatement preparedStatement = Dbaconnection.getConnection().prepareStatement(queryInsertEmployer);
try {
try (ResultSet resultSet = Dbaconnection.getConnection().createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY).executeQuery(queryInsertEmployer)) {
if (resultSet.next()) {
File tempBackgroundDirectory = new File("src/Temporary/Temp/Pictures");
/*check your package if exist or not*/
if (!tempBackgroundDirectory.exists()) {
tempBackgroundDirectory.mkdirs();
}
/*define a default name of your image*/
imageFile = new File("src/Temporary/Temp/Pictures/temp-user-image.jpg");
/*set your file in outputStream*/
fos = new FileOutputStream(imageFile);
byte[] buffer = new byte[1];
InputStream is = resultSet.getBinaryStream(1);
if (is != null) {
userImage = new Image(is);
while (is.read(buffer) > 0) {
fos.write(buffer);
}
}
}
fos.close();
}
if (imageFile.delete()) {
System.out.println("Temporary image was deleted.");
}else
{
System.out.println("There is some troubles");
}
} catch (SQLException ex) {
ex.printStackTrace();
}
} catch (SQLException ex) {
ex.printStackTrace();
}
/*Return the result of your method*/
return userImage;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment