使用 Java 将图像保存到文件的最佳方法是什么?
我有一项学校作业,需要将任意图像与其他数据一起保存到磁盘上的单个文件中。
我们考虑将其与数据一起序列化;但是,图像,甚至是 BufferedImage,都无法序列化。
使用 Java 将图像与其他数据保存在单个文件中的最佳最简单方法是什么?老实说,我不太关心文件大小。不过,如果它被压缩,我认为这是一个优点。
I have a school work where I need to save an arbitrary image to the disk along with other data, in a single file.
We thought about serializing it, along with the data; however, images, even BufferedImage
s, can't be serialized.
What's the best simplest way to save an image with other data in a single file, using Java? Honestly, I don't really care about the file size. Though, if it's compressed, I suppose it's a plus.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
其中 img 是您的 BufferedImage。
之后,您可以使用 FileOutputStream 打开文件并在其后面或后面写入一些数据。
阅读时,您只需剪切附加数据并将其余部分视为您的图像。
where img is your
BufferedImage
.After that you can open the file with
FileOutputStream
and write some data after or behind.When reading you just have to cut the appended data and treat the rest as your image.
如果您想要一个“可读”的解决方案,例如存储在文本文件中,您可以将图像编码为 base64 字符串并将其存储在文件中。对于 Java,这个问题中有几个选项,例如来自 apache 公共资源。
如果您得到
byte[]
如其他答案所示,您可以通过执行以下操作来获取字符串并获取字节数组
If you want a "readable" solution, as in store in a text file, you could encode the image as a base64 string and store that in your file. There are a few options in this question for Java, for instance the one from apache commons.
If you get the
byte[]
as illustrated in the other answers you can get a String by doingAnd get the byte array back with