使用Java以二进制格式将图像存储在数据库中 [英] Storing Image in Data Base Using Java in Binary Format

查看:218
本文介绍了使用Java以二进制格式将图像存储在数据库中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究项目,但遇到了一些问题,我进行了搜索,但找不到完整的学习资源,我需要使用Java程序将图像存储在SQL Server数据库中,并且需要返回要检索,图像的尺寸不大,它们的范围在30到50 K之间, 我可以使用toolKit中的getImage()方法从磁盘中加载图像

I am working around my project and got some Problem, I searched for it , but couldn't find meaning full learning resource, What I need is to Store Image in SQL Server Database using my Java program , and will need that Back to Retrieve, images are not of larger size they are ranging between 30 and 50 K, I can load images from my Disk by using getImage() method in toolKit

Image imm = Toolkit.getDefaultToolkit().getImage("URl");

,但是我不知道如何将该图像转换为二进制格式并存储在数据库中,然后从数据库中检索回来. 我想通过查看几个站点将其存储在VarBinary中,我发现SQL Server中的图像类型即将退役.

, but i don't know How to convert that image to Binary Format and to store in Database, and then retrieve Back From Database. I want to Store that in VarBinary s by looking around several sites i found that the image type in SQL Server is soon going to Retire.

推荐答案

尽管在数据库中存储很大的二进制对象不是一个好主意,但Microsoft研究论文"表示如果对象大小小于256K.因此,听起来您已经达到了可存储3万张图像的数据库存储的最佳位置.

While it's not a good idea to store very large binary objects in the database, the Microsoft research paper "To BLOB or Not To BLOB: Large Object Storage in a Database or a Filesystem" indicates it's an efficient approach if object sizes are less than 256K. So it sounds like you've hit the sweet spot for database storage with 30K images.

您可以使用以下网址从URL加载图像作为缓冲图像:

You can load your image as a buffered image from a URL using:

BufferedImage imm = ImageIO.read(url);

然后使用以下命令将其转换为字节数组:

Then convert it to a byte array with:

byte[] immAsBytes = 
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//use another encoding if JPG is innappropriate for you
ImageIO.write(imm, "jpg", baos );
baos.flush();
byte[] immAsBytes = baos.toByteArray();
baos.close();

然后存储字节数组

Then store the byte array as recommended by this article as a VARBINARY in the database. In your JDBC code, you should wrap the byte array in a ByteArrayInputStream and set the PreparedStatement parameter as a BinaryStream:

PreparedStatement pstmt = commection.prepareStatement("INSERT INTO IMAGES (image) VALUES(?)");
ByteArrayInputStream bais = new ByteArrayInputStream(immAsBytes);
pstmt.setBinaryStream(1, bais, immAsBytes.length);
pstmt.executeUpdate();
pstmt.close();

要从数据库中取出图像,请使用ResultStatement.getBlob():

To get the image out of the database, use ResultStatement.getBlob():

Blob immAsBlob = rs.getBlob();
byte[] immAsBytes = immAsBlob.getBytes(1, (int)immAsBlob.length()));

最后,将字节数组转换为BufferedImage并对其进行处理:

Finally, convert the byte array to a BufferedImage and do something with it:

InputStream in = new ByteArrayInputStream(immAsBytes);
BufferedImage imgFromDb = ImageIO.read(in);

这篇关于使用Java以二进制格式将图像存储在数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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