将 BufferedInputStream 转换为图像 [英] Convert BufferedInputStream into image

查看:32
本文介绍了将 BufferedInputStream 转换为图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法将我的 blob 转换为缓冲图像以便我可以使用它.我从我使用输入流上传的数据库中获取了一个 blob(jpg 图像).在我的数据库中,它存储为 BufferedInputStream 我注意到.我得到的 blob 很好,它是一堆奇怪的符号,并说它是 jpg,所以图像必须没问题.谁能发现我做错了什么?也许我转换错了?在 image = ImageIO.read(new ByteArrayInputStream(data));图片返回空.

Im having trouble turning my blob into a buffered image so I can use it. I'm getting a blob (jpg image) back from my database I uploaded using inputstream. In my database it is stored as BufferedInputStream I notice. I get the blob just fine, its a bunch of weird symbols and says its a jpg so the image has to be fine. Can anyone spot what I'm doing wrong? Maybe im converting it wrong? At image = ImageIO.read(new ByteArrayInputStream(data)); Image returns null.

@GET
@Path("{id}")
 @Produces("image/*")
public Response post(@PathParam("id") String id) throws IOException {
    Connection con = connection();
    Blob blob = getPhoto(con);
    BufferedImage image = null;
    byte[] data = null;
    int blobLength = 0;
    try {
        blobLength = (int) blob.length();
        data = blob.getBytes(1, blobLength);
        image = ImageIO.read(new ByteArrayInputStream(data));
    //  ImageIO.write(image, "JPEG", new File("C:/Users/Nicolas/Desktop/image.jpg"));
    } catch (SQLException e2) {
        e2.printStackTrace();
    }  

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

我如何写入数据库

public void postPhoto(Connection con, InputStream uploadedInputStream){

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

我如何将文件发送到我的 servlet

How I send the file to my servlet

var fileInput = document.getElementById('file');
var file = fileInput.files[0];
var formData = new FormData();
formData.append("file", file);

var parameters="first="+firstName+"&last="+lastName+"&file="+file;

xmlhttp.open("post","http://localhost:8080/restService/api/submitinfo",true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send(formData);

推荐答案

首先验证 uploadedInputStream 是一个有效的图像,然后使用 ImageIO.write 写出它.您始终可以使用 ImageIO.read 读回图像并将其写回 ByteArrayInputStream ;)

Start by verifying that uploadedInputStream is a valid image, prehaps by writing it out using ImageIO.write. You can always use ImageIO.read to read the image back in and write it back out to a ByteArrayInputStream ;)

我使用 H2 数据库做了一个快速测试.

I did a quick test using H2 database.

我注意到的一些事情.Blob#length 返回一个 long,而 Blob#getBytes 需要一个 int,这可能意味着您正在截断字节流.

A few things I noted. Blob#length returns a long, while Blob#getBytes expects an int, this could mean you're truncating the byte stream.

另外,从 H2 的文档来看,Blob 的内容似乎没有保存在内存中,所以我使用 getBinaryStream 代替.

Also, from the documentation of H2, it would seem that the Blob contents is not kept in memory, so I use the getBinaryStream instead.

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;

public class TestImageDatbase {

    private Connection con;

    public static void main(String[] args) {
        new TestImageDatbase();
    }

    public TestImageDatbase() {
        try {
            clearDatabase();
            saveImage();
            loadImage();
        } catch (ClassNotFoundException | SQLException | IOException exp) {
            exp.printStackTrace();
        }
    }

    protected Connection getConnection() throws ClassNotFoundException, SQLException {
        Class.forName("org.h2.Driver");
        return DriverManager.getConnection("jdbc:h2:d:\\Image", "sa", "");
    }

    protected void clearDatabase() throws IOException, ClassNotFoundException, SQLException {

        Connection con = null;
        PreparedStatement stmt = null;

        try {

            con = getConnection();
            System.out.println("Cleaning database");
            stmt = con.prepareStatement("delete from images");
            int updated = stmt.executeUpdate();
            System.out.println("Updated " + updated + " rows");

        } finally {
            try {
                stmt.close();
            } catch (Exception e) {
            }
            try {
                con.close();
            } catch (Exception e) {
            }
        }

    }

    protected void saveImage() throws IOException, ClassNotFoundException, SQLException {

        Connection con = null;
        PreparedStatement stmt = null;
        ByteArrayOutputStream baos = null;
        ByteArrayInputStream bais = null;

        try {

            baos = new ByteArrayOutputStream();

            File source = new File("/path/to/file");
            System.out.println("Source size = " + source.length());
            BufferedImage img = ImageIO.read(source);
            ImageIO.write(img, "png", baos);

            baos.close();

            bais = new ByteArrayInputStream(baos.toByteArray());

            con = getConnection();
            stmt = con.prepareStatement("insert into images (image) values (?)");
            stmt.setBinaryStream(1, bais);
            int updated = stmt.executeUpdate();
            System.out.println("Updated " + updated + " rows");

        } finally {
            try {
                bais.close();
            } catch (Exception e) {
            }
            try {
                baos.close();
            } catch (Exception e) {
            }
            try {
                stmt.close();
            } catch (Exception e) {
            }
            try {
                con.close();
            } catch (Exception e) {
            }
        }

    }

    protected void loadImage() throws IOException, ClassNotFoundException, SQLException {

        Connection con = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;

        try {

            con = getConnection();
            stmt = con.prepareStatement("select image from images");
            rs = stmt.executeQuery();

            while (rs.next()) {

                System.out.println("Getting blob");
                Blob blob = rs.getBlob(1);
                System.out.println("Reading image");
                BufferedImage img = ImageIO.read(blob.getBinaryStream());
                System.out.println("img = " + img);
                JOptionPane.showMessageDialog(null, new JScrollPane(new JLabel(new ImageIcon(img))));

            }

        } finally {
            try {
                rs.close();
            } catch (Exception e) {
            }
            try {
                stmt.close();
            } catch (Exception e) {
            }
            try {
                con.close();
            } catch (Exception e) {
            }
        }

    }

}

这篇关于将 BufferedInputStream 转换为图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆