首页 > 解决方案 > 使用准备好的语句以 blob 格式将图像插入数据库

问题描述

我想在加密后使用 Java 中的 Prepared Statement 以 blob 格式在 DB 行中插入图像。我正在使用自定义加密函数,并且在另一端使用相应的解密函数将 blob 解密回图像(我不参与解密部分,只参与加密)。问题是解密后的图像不是原始图像。这是一个非常小的白色图像,所以我认为我的过程中有些地方是不正确的,我非常感谢任何反馈或想法。这是代码:

// already existing code
...
String photo_str    // contains the photo
int id = 1;     // for this example 
byte[] blobBytes = new sun.misc.BASE64Decoder().decodeBuffer(photo_str);

BufferedImage image = ImageIO.read(new ByteArrayInputStream(blobBytes));
ByteArrayOutputStream stream = new ByteArrayOutputStream();
ImageIO.write(image, type, stream);
input.set(photo_str, stream.toByteArray());   // this sets the photo_str field (String) to the second argument

// my code
byte[] blobBytes = photo_str.getBytes();
byte[] blob = CustomEncrypt(id, blobBytes);  // custom encryption function
InputStream targetStream = new ByteArrayInputStream(blob);

String updateString = "UPDATE MY_TABLE SET PHOTO=? WHERE ID=?";
PreparedStatement ps = con.prepareStatement(updateString);
ps.setBlob(1, targetStream, blob.length);
ps.setString(2, id);
int rows = ps.executeUpdate();

我已经有了字符串格式的图像,据我所知,这是字节数组中字节的序列,所以问题出在我转换为字节数组然后写入输入流时?

先感谢您。

标签: javasqlencryptionblobprepared-statement

解决方案


推荐阅读