-1

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
  • What have you tried? What are you getting? How is the image saved in the DB, as base 64? Commented Jun 16, 2016 at 11:21
  • Image saves as binary, can i convert it as image file
    – Raja Doss
    Commented Jun 16, 2016 at 11:29

2 Answers 2

2

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();
    }
}
1
  • 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
    – Raja Doss
    Commented Jun 16, 2016 at 12:16
0

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

1
  • How to convert bytes to image and preview?
    – Raja Doss
    Commented Jun 16, 2016 at 12:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.