如何在Spark Java上使用/ get路由返回图像,以便它显示在网页上?

时间:2018-03-04 00:13:22

标签: java mysql

正如标题所说,我正在尝试使用Spark Java在网页上显示图像。我试图检索的图像使用mysql存储为MEDIUMBLOB。

    File file = new File("image.jpg");
    FileOutputStream output = new FileOutputStream(file);
    BufferedImage bi = null;
        System.out.println("Writing to File: " + file.getAbsolutePath());
        try {


            String sql = "SELECT Image FROM images WHERE Image_ID = 0;";
            PreparedStatement statement = db.conn.prepareStatement(sql);
            ResultSet rs = statement.executeQuery();
            //writes image to file to make sure it the image come out right
            while(rs.next()){
                InputStream input = rs.getBinaryStream("Image");
                bi = ImageIO.read(input);
                int available = input.available();
                byte[] buffer = new byte[available];
                while(input.read(buffer) > 0){
                    output.write(buffer);
                }
            }



            } catch (Exception e) {
            System.out.println(e);
        }



    return bi;

我正在使用HTML表单调用该函数:

    <div class="get_file">
        <form method="get" action="/mainpage">
            <input type = "submit">
        </form>
    </div>

当我运行程序时,它不是显示图像而是给我这个文本:

  

BufferedImage @ 4b72a5d2:type = 5 ColorModel:#pixelBits = 24 numComponents = 3&gt; color space = java.awt.color.ICC_ColorSpace@68f38796 transparency = 1 has alpha&gt; = false isAlphaPre = false ByteInterleavedRaster:width = 274 height = 184&gt; #numDataElements 3 dataOff [0] = 2

1 个答案:

答案 0 :(得分:0)

返回值实际上是BufferedImage,您应该返回一个字节数组。我建议为此目的使用ByteArrayOutputStream。

    byte[] rawImage = null;
    try(ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        ImageIO.write( bi, "jpg", baos );

        baos.flush();
        rawImage = baos.toByteArray();
    }

    return rawImage;

---- EDITED ----

确保包含&#34;内容类型&#34;通过指定&#34; image / jpeg&#34;

在您的回复中添加标题