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

问题描述 投票:0回答:1

正如标题所说,我正在尝试使用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> color space = java.awt.color.ICC_ColorSpace@68f38796 transparency = 1 has alpha> = false isAlphaPre = false ByteInterleavedRaster:width = 274 height = 184># numDataElements 3 dataOff [0] = 2

java mysql
1个回答
0
投票

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

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

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

    return rawImage;

----编辑----

确保通过指定“image / jpeg”在响应中包含“Content-Type”标题

© www.soinside.com 2019 - 2024. All rights reserved.