如何将 BufferedImage 对象转换为 InputStream 或 BLOB?
我正在尝试使用 LONGBLOB
属性将用户上传的图像存储到数据库中...我遇到了 PreparedStatement
的问题,它有两种方法来设置Blob 分别是:
public void setBinaryStream(intparameterIndex, InputStream x)
public void setBlob(intparameterIndex, Blob x)
public void setBlob(intparameterIndex, InputStream) inputStream)
现在的问题是我有一个 BufferedImage
对象,必须将其转换为 Blob
或 InputStream
才能上传...
如何我可以在不丢失原始图像格式或质量的情况下执行此操作吗?
I am trying to store an image uploaded by the user into the database with a LONGBLOB
attribute... I ran into a problem with a PreparedStatement
that has two methods to set a blob which are:
public void setBinaryStream(int parameterIndex, InputStream x)
public void setBlob(int parameterIndex, Blob x)
public void setBlob(int parameterIndex, InputStream inputStream)
Now the problem is I have a BufferedImage
object which must be converted into Blob
or InputStream
to upload...
How can I do this without losing the original image format or quality?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要使用某种适当的(无损)格式保存它。 png 格式 是一种选择。
ImageIO
类具有用于写入的方法将图像输出到输出流。以下是如何获取
InputStream
的完整示例,您可以从中读取BufferedImage
内容的 PNG 表示形式:You need to save it using some appropriate (lossless) format. The png format is one option.
The
ImageIO
class has methods for writing out an image to an output stream.Here's a complete example of how you get hold of an
InputStream
from which you can read the PNG-representation of the content of aBufferedImage
:下面是示例代码:
不要忘记检查第二个 ImageIO.write 参数是否符合您所需的图像格式(例如“jpg”、“bmp”、“png”)。
Here is a sample code:
Don't forget to check the second ImageIO.write parameter to your required image format (e.g. "jpg", "bmp", "png").
编写函数来序列化/反序列化 BufferedImage
到/从
byte []
并使用类ByteArrayInputStream
和ByteArrayOutputStream
。您可能需要序列化图像类型、宽度、高度
和图像像素值(通过 BufferedImage.getRGB(x, y) 获得)。
另一种方法是调用 ImageIO.write(image, "png", outStream)
将图像转换为 PNG 格式并将其写入
ByteArrayOutputStream
。有一个等效的ImageIO.read(inputStream)
方法从 ByteArrayInputStream 读取图像。
与 PNG 之间的转换会产生一些处理开销。
但PNG是一种压缩图像格式,你会节省很多
与存储未压缩的图像相比,节省了空间。
Write functions to serialize/unserialize the BufferedImage
to/from a
byte []
and use classesByteArrayInputStream
andByteArrayOutputStream
.You probably need to serialize the image type, width, height
and the image pixel values (obtained with
BufferedImage.getRGB(x, y)
).The alternative is to call
ImageIO.write(image, "png", outStream)
to convert the image to PNG format and write it to a
ByteArrayOutputStream
. There is an equivalentImageIO.read(inputStream)
method to read the image from a
ByteArrayInputStream
.There is some processing overhead in converting to/from PNG.
But PNG is a compressed image format and you will save a lot
of space compared with storing the images uncompressed.
要创建 Blob:
To create a Blob: