使用Java在Postgresql中存储和检索图像 [英] Store and retrieve images in Postgresql using Java

查看:462
本文介绍了使用Java在Postgresql中存储和检索图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java编程新手,我正在搜索Java代码以在PostgreSQL中存储图像并检索图像。

I am new to Java programming, I am searching for Java code to store images in PostgreSQL and to retrieve the image.

在PostgreSQL中,我使用了Bytea Data-type。图像已存储。但是当我检索时我得到了NULL。我无法获得图像。

In PostgreSQL I have used Bytea Data-type. the image was stored. but when I retrieve I am getting NULL. I cant get the image.

对此或任何其他建议的任何示例都会有所帮助。

Any example for this or any other suggestion on this would be helpful.

推荐答案

第7章涉及存储二进制数据并使用图像(* .gif文件)作为示例。你可能想读它。

chapter 7 of the postgresql jdbc documentation deals with storing binary data and uses an image (*.gif file) an an example. you might want to read it.

将图像插入数据库(来自上面的链接)

inserting an image into the db (from the link above)

File file = new File("myimage.gif");
FileInputStream fis = new FileInputStream(file);
PreparedStatement ps = conn.prepareStatement("INSERT INTO images VALUES (?, ?)");
ps.setString(1, file.getName());
ps.setBinaryStream(2, fis, (int)file.length());
ps.executeUpdate();
ps.close();
fis.close();

从数据库中读取图像(也来自上面的链接)

reading an image from the db (also from the link above)

// Get the Large Object Manager to perform operations with
LargeObjectManager lobj = ((org.postgresql.PGConnection)conn).getLargeObjectAPI();

PreparedStatement ps = conn.prepareStatement("SELECT imgoid FROM imageslo WHERE imgname = ?");
ps.setString(1, "myimage.gif");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
    // Open the large object for reading
    int oid = rs.getInt(1);
    LargeObject obj = lobj.open(oid, LargeObjectManager.READ);

    // Read the data
    byte buf[] = new byte[obj.size()];
    obj.read(buf, 0, obj.size());
    // Do something with the data read here

    // Close the object
    obj.close();
}
rs.close();
ps.close();

这篇关于使用Java在Postgresql中存储和检索图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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