简体   繁体   English

ImageIO.read在字节数组上返回null

[英]ImageIO.read returns null on byte array

Here is my code. 这是我的代码。 I get a blob from my database. 我从我的数据库中得到一个blob。 Which is returned to me like this: java.io.BufferedInputStream@16e31e37. 哪个像这样返回给我:java.io.BufferedInputStream@16e31e37。 Now im trying to display the image from my servlet in the browser however my BufferedImage image is always null. 现在我试图在浏览器中显示来自我的servlet的图像,但是我的BufferedImage图像始终为null。 I dubugged it and notice my blob length is always 34.. Not matter the image. 我对它进行了调整,并注意到我的斑点长度始终为34 ..无论图像如何。

@Path("/photo" )
public class DisplayPhoto { 

@GET
@Path("{id}")
 @Produces("image/*")
public Response post(@PathParam("id") String id) throws IOException {
    Connection con = connection();
    Blob blob = getPhoto(con);




    int blobLength = 0;
    try {
        blobLength = (int) blob.length();
    } catch (SQLException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
    }  
    byte[] data = null;
    try {
        data = blob.getBytes(1, blobLength);
    } catch (SQLException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    BufferedImage image = null;
    try {
    image = ImageIO.read(new ByteArrayInputStream(data));
//  ImageIO.write(image, "JPEG", new File("C:/Users/Nicolas/Desktop")); // writing image to some specific folder.

    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }



    return Response.ok(image).build();

}



public Connection connection(){
    Connection con = null;

    try {// set up driver for database
        Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }


    try {
        con = DriverManager.getConnection("jdbc:mysql://aa1c9da17owdhky.cotr7twg0ekb.us-west-2.rds.amazonaws.com/test","nightskycode","uocb4t111");
    //  boolean reachable = con.isValid(10);// check for connection to DB


    } catch (SQLException e) {
        e.printStackTrace();
        System.out.println("No go!3");
    }
    return con;
  }

public Blob getPhoto(Connection con){

    Blob photo = null;
    Statement stmt = null;
    ResultSet rs = null;


    try {
        stmt = con.createStatement();
        rs = stmt.executeQuery("Select photo from photos where photo_id = 7");

        if (stmt.execute("Select photo from photos where photo_id = 7")) {
            rs = stmt.getResultSet();

            while (rs.next()) { // results here
           photo =  rs.getBlob("photo");
            System.out.println(rs.getString("photo")); }
        }

    } 
    catch (SQLException ex){
        // handle any errors
        System.out.println("SQLException: " + ex.getMessage());
        System.out.println("SQLState: " + ex.getSQLState());
        System.out.println("VendorError: " + ex.getErrorCode());
    }
    return photo;

}

Here is how I am uploading my data to the database 以下是我将数据上传到数据库的方法

@Path("/submitinfo" )
public class SubmitName {   

@POST
@Produces(MediaType.APPLICATION_XML)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public String post(@FormDataParam("file") InputStream uploadedInputStream, @FormParam("first") String name) {
    Connection con = connection();

    postName(con, name);
    postPhoto(con, uploadedInputStream);
    return name; 


}


public void postPhoto(Connection con, InputStream uploadedInputStream){


    Statement stmt = null;
    String updateQuery = "INSERT INTO photos (photo) values ('" + uploadedInputStream + "')" ;
    System.out.println(updateQuery);

    try {
        stmt = con.createStatement();
        stmt.executeUpdate(updateQuery);
        con.close(); // Close the connection

    } catch (SQLException e) {
        e.printStackTrace();

    }

}

The problem is how you're trying to store data as a blob. 问题是你如何尝试将数据存储为blob。 You need to use a PreparedStatement - specifically, with its setBlob() method: 您需要使用PreparedStatement - 特别是使用setBlob()方法:

String mySQL = "INSERT INTO photos (photo) values (?)";
PreparedStatement pStmt = con.prepareStatement(mySQL);
pStmt.setBlob(1, uploadedInputStream);
pStmt.execute();

Edit to add: The reason it isn't working now is because you're concatenating a String to create your SQL and you're getting the result of InputStream.toString() which is what you see being stored - it's the default Object.toString() which is a combination of the class name and hashcode. 编辑添加:它现在不工作的原因是因为你连接一个String来创建你的SQL,你得到的是InputStream.toString()的结果,这是你看到的存储 - 它是默认的Object.toString() ,它是类名和哈希码的组合。

And really you should always use PreparedStatement s. 实际上你应该总是使用PreparedStatement Not only does it make for cleaner code, it handles quoting/escaping for you which is less error prone. 它不仅可以实现更清晰的代码,还可以为您处理引用/转义,而不易出错。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM