I can store image file to database but how can I get the image as a file and preview using java , it's like quikr image uploading
2 Answers
Following code will store and retrieve images to MySql DB.
Store image into DB
public static void main(String args[]){
try{
// DB connection
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost/your db name","root","root");
File file=new File("E:\\sample_image.png");
FileInputStream fis=new FileInputStream(file);
//Insert image into db
PreparedStatement ps=con.prepareStatement("insert into image_table (name,image) values(?,?)");
ps.setString(1,"image 1");
ps.setBinaryStream(2,fis,(int)file.length());
ps.executeUpdate();
ps.close();
fis.close();
con.close();
}catch(Exception e){
e.printStackTrace();
}
}
Retrieve image into DB
Below code will retrieve image from database and save it @ location "E:\sample_image.png".
public static void main(String args[]){
try{
// DB connection
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost/your db name","root","root");
File file=new File("E:\\sample_image.png");
FileOutputStream fos=new FileOutputStream(file);
byte b[];
Blob blob;
PreparedStatement ps=con.prepareStatement("select * from image_table");
ResultSet rs=ps.executeQuery();
while(rs.next()){
blob=rs.getBlob("image");
b=blob.getBytes(1,(int)blob.length());
fos.write(b);
}
ps.close();
fis.close();
con.close();
}catch(Exception e){
e.printStackTrace();
}
}
-
It's web app ,i don't want save in local memory, i want to restore the byte and convert it to image file. But not save in local memory Commented Jun 16, 2016 at 12:16
Convert the Image
to Bytes
, save to db or restore from db in bytes
Check this answer to convert to bytes or this answer which is like your problem
Check this for byte to image operations