图像不会出现在Web浏览器中

时间:2015-08-04 08:15:27

标签: java database eclipse browser get

这是我在eclipse中的Java代码:

   @GET
    @Path("request=getTile")
    @Produces({"image/png"})
    public BufferedImage getTileGET(@QueryParam("id_photo")String id_photo,
                          @QueryParam("x")String x, 
                          @QueryParam("y")String y, 
                          @QueryParam("zoom")String zoom) throws SQLException, IOException  {

        BufferedImage BI = null;
        connection dbs = new connection();
        Statement statement = null;
        Connection con = dbs.getConnection();
        PreparedStatement ps = null;

        try {
            ps = con.prepareStatement("SELECT image from tiles where id_photo = '"+id_photo+"' "
                    + "and x ='"+x+"' and y ='"+y+"' and zoom = '"+zoom+"';");

            ResultSet rs = ps.executeQuery();

                while (rs.next()) {
                    InputStream input = rs.getBinaryStream("image");
                    BI=ImageIO.read(input); 
                    input.close();  
                }

        }     
        catch (SQLException e )
        {
            e.printStackTrace();
            System.out.println("Bad data");
        }
        finally {
            if (statement != null) {
                statement.close();
            }

            if (con != null) {
                con.close();
            }
        }       
        return BI;
        }

我的问题是图片未显示在浏览器(Google Chrome)中。 我在数据库中的图像是bytea。我究竟做错了什么?谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

你不能简单地返回那样的图像。请参阅此示例:https://stackoverflow.com/a/9204824/1256583

@GET
@Path("request=getTile")
@Produces({"image/png"})
public Response getTileGET(...) {

    BufferedImage image = ...;

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(image, "png", baos);
    byte[] imageData = baos.toByteArray();

    // uncomment line below to send non-streamed
    // return Response.ok(imageData).build();

    // uncomment line below to send streamed
    // return Response.ok(new ByteArrayInputStream(imageData)).build();