在PostgreSQL中存储图像

5

我正在尝试将图片存储在Postgresql数据库中,我有一个用于将图像存储在数据库中的过程,图像列类型为bytea。 我尝试将我的图像转换为字符串(Base64),并将其转换为byte [],但无法更新该图像。

读取图像并将其转换为字符串的代码如下:

 File file = new File("FilePath\\image.jpg");

 try
 {
     // Reading a Image file from file system
     FileInputStream imageInFile = new FileInputStream(file);
     byte imageData[] = new byte[(int) file.length()];
     imageInFile.read(imageData);

     // Converting Image byte array into Base64 String By calling encodeImage Function
     byte[] imageDataString = encodeImage(imageData);

     CallableStatement statement = con.prepareCall(" { call products_update_image( '" + id + "', '" + imageDataString + "') } ");
     statement.execute();
 }
 catch (Exception ex)
 {
     System.out.println("Exception is:- " + ex);
 }

 public static byte[] encodeImage(byte[] imageByteArray)
 {
     return Base64.encodeBase64(imageByteArray);
 }

我使用这个链接将图像转换为字符串链接 以下是用于在数据库中保存图像的过程。

CREATE OR REPLACE FUNCTION UpdateProfileImage(product_id character varying, img bytea)

有人能告诉我为什么我无法存储这张图片,或者我做错了什么吗?


1
为什么不将图像读入ByteArrayOutputStream中,这样您就可以访问byte[]数据了呢? - MadProgrammer
@MadProgrammer 我在这里放了一些代码,你可以检查一下。我还指定了一个链接,用于将图像转换为字符串。 - Luffy
你得到了什么错误? - user330315
@a_horse_with_no_name 我没有收到任何错误信息,也许它没有将图像更新到数据库中。 - Luffy
1
使用PreparedStatementsetBinaryStream(),例如:https://dev59.com/CGsy5IYBdhLWcg3wvgn7#8349906或http://stackoverflow.com/a/4339778/330315。 - user330315
显示剩余4条评论
1个回答

3
感谢a_horse_with_no_name的帮助,我找到了解决我的问题的方法。我不需要调用存储图像的过程,而是需要将图像作为二进制流传递。
PreparedStatement pstmt = con.prepareStatement("UPDATE PRODUCTS SET IMAGE = ? WHERE ID = ?");
File file = new File("C:\\Program Files (x86)\\openbravopos-2.30.2\\image.jpg");
FileInputStream in = new FileInputStream(file);
try
{
    pstmt.setBinaryStream(1, in, (int) file.length());
    pstmt.setString(2, id);
    pstmt.executeUpdate();
    //con.commit
}
catch (Exception ee)
{
    System.out.println("Exception is:- " + ee);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接