1

I am using mysql as my database. I am getting byte array in my java code. Then I am storing this byte array in Database as LONGBLOB. Now while retrieving it back from db, I am using below code:

package com.sendSms;
import java.awt.image.BufferedImage;
import java.io.*;
import java.sql.*;
import javax.imageio.ImageIO;
import org.apache.commons.io.IOUtils;
public class SampleTest {
    public Connection getConnection(){
        Connection con=null;
        try{
            Class.forName("com.mysql.jdbc.Driver");
            con=DriverManager.getConnection("jdbc:mysql://localhost:3306/forTest","root","123456");
        }catch(Exception ex){}
        return con;
    }
    public byte[] getFromDb(){
        byte[] arr=null;
        try{
            Connection con = getConnection();
            PreparedStatement pstmt=con.prepareStatement("select id,image from TestAndroid where id = ?");
            pstmt.setInt(1, 16);
            ResultSet rs = pstmt.executeQuery();
            while(rs.next()){
            //  int id=rs.getInt("id");

                arr = rs.getBytes("image");
            }
        }
        catch(Exception ex){ex.printStackTrace();}

        return arr;
    }
    public void go() throws IOException{
        byte[] arr=getFromDb();
        InputStream is=new ByteArrayInputStream(arr);
        BufferedImage bi= ImageIO.read(is);
        if(bi==null){
            System.out.println("bi is NULL");
        }
        else{
            System.out.println("bi is NOT NULL");
        }
    }
    public static void main(String[] args) throws IOException {
        SampleTest st = new SampleTest();
        st.go();
    }

}

When I am running this code I am getting BufferedImage as null; although byte array is Not Null at this point. How can get this BufferedImage. I need BufferedImage because I need to pass it to other function, that accepts only BufferedImage. How can I resolve this issue.

Also when storing byte array in db, I am using:

setBytes(byte array) method on PreparedStatement & in Db I am using LONGBLOB data type for storing this byte array.

Lukasz Re
  • 79
  • 1
  • 11
JPG
  • 1,247
  • 5
  • 31
  • 64

1 Answers1

1

The javadoc for the ImageIO.read(InputStream is) method states:

If no registered ImageReader claims to be able to read the resulting stream, null is returned.

It might be that your byte array does not represent a valid image format?

Matt
  • 3,677
  • 1
  • 14
  • 24