如何将Java中的图片保存为多个blob?

时间:2014-04-14 16:37:10

标签: java image blob inputstream fileinputstream

正如我在标题中所描述的那样,我尝试使用InputStream多次访问图片文件,然后将其保存到blob类型数据库,但结果对于第二个,第三个,等等为null。以下是代码片段:

File image1 = new File("src/template1.png").getAbsoluteFile();
File image2 = new File("src/template2.png").getAbsoluteFile();
InputStream in1 = new FileInputStream(image1);
InputStream in2 = new FileInputStream(image2);
long length1 = image1.length();
long length2 = image2.length();
pstmt.setString(1, jTextField18.getText().toUpperCase());
pstmt.setBlob( 2, in1, length1 );
pstmt.setBlob( 3, in1, length1 );
pstmt.setBlob( 4, in1, length1 );
pstmt.setBlob( 5, in1, length1 );
pstmt.setBlob( 6, in1, length1 );
pstmt.setBlob( 7, in2, length2 );
Pstmt.setBlob( 8, in2, length2 );

然后结果是:

YR/21
[BLOB - 5.6 KiB]
[BLOB - 0 B]
[BLOB - 0 B]
[BLOB - 0 B]
[BLOB - 0 B]
[BLOB - 5.5 KiB]
[BLOB - 0 B]

我尝试使用此代码的新InputStream,并发生了其他错误。它说: 行大小太大(> 8126)。将某些列更改为TEXT或BLOB或使用ROW_FORMAT = DINAMIC或ROW_FORMAT = COMPRESSED可能会有所帮助。在当前行格式中,760字节的BLOB前缀以内联方式存储。

pstmt.setBlob( 2, in1, length1 );
image1 = new File("src/template1.png").getAbsoluteFile();
in1 = new FileInputStream(image1);
pstmt.setBlob( 3, in1, length1 );
image1 = new File("src/template1.png").getAbsoluteFile();
in1 = new FileInputStream(image1);
pstmt.setBlob( 4, in1, length1 );

我认为问题得到解决并转变为另一个问题。谢谢你的回答

2 个答案:

答案 0 :(得分:2)

第一个调用消耗流,后续调用不获取数据。每次调用都需要一个单独的InputStream。

答案 1 :(得分:0)

“有没有办法将图片保存到多个blob?”

是的,但您的代码仅适用于小图片。相反,有一个图像的父引用和实际图像的子代,它们将具有blob。让孩子们变小,只为每一个孩子保存一大块图像。

这将有助于您管理空间,并且更容易备份。

有关如何以块的形式读取文件的参考,请查看此处:http://www.javapractices.com/topic/TopicAction.do?Id=245

使用读取文件的while循环将图像块保存到数据库中。

保存文件可能是一项冗长的操作,因此您可以在父项上有一个标志,用于定义子项是否全部加载。从而防止其他线程读取不完整的图像。

如果您使用的是MySQL,那么本教程将介绍如何读取和写入图像:http://zetcode.com/db/mysqljava/

玩得开心。