0

I am storing some images in a MySQL database using

ps.setBinaryStream(1, photo);

where photo is an InputStream.

When I read the image from database, I need to convert it to a byte[]. How can I do this?

2
  • 1
    Surely any JDBC tutorial would cover this...have you tried something yet? Commented Dec 24, 2017 at 9:41
  • 1
    Have you tried ResultSet.getBytes(..)? Commented Dec 24, 2017 at 9:56

2 Answers 2

1

All you need to do is a statement and a result set. Something like this:

Statement myStatement=(Statement) myConnection.createStatement();
ResultSet myRS=myStatement.executeQuery(mySQLstring);
byte[] photo = myRS.getBytes("myphotoColumnLabel");
Sign up to request clarification or add additional context in comments.

Comments

1

You could try something like:

        File file=new File("E:\\image1.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);
        }

The maximum length of Blob type is 64kb.Use bigger types like mediumblob or longblob.

You can also retrieve by using : inputStream imgStream = resultSet.getBinaryStream(1); as you stored the image using InputStream

1 Comment

Have you actually tried this? With larger images? There is a limit on the size of byte-arrays yuo can write to a FileOutputStream at least with some JVMs out there.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.