使用 Java 将图像保存到文件的最佳方法是什么?

发布于 2024-10-06 08:11:59 字数 194 浏览 8 评论 0原文

我有一项学校作业,需要将任意图像与其他数据一起保存到磁盘上的单个文件中。

我们考虑将其与数据一起序列化;但是,图像,甚至是 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 BufferedImages, 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

云胡 2024-10-13 08:11:59
ImageIO.write(img, "BMP", new File("filename.bmp"));

其中 img 是您的 BufferedImage。

之后,您可以使用 FileOutputStream 打开文件并在其后面或后面写入一些数据。
阅读时,您只需剪切附加数据并将其余部分视为您的图像。

ImageIO.write(img, "BMP", new File("filename.bmp"));

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.

长亭外,古道边 2024-10-13 08:11:59

如果您想要一个“可读”的解决方案,例如存储在文本文件中,您可以将图像编码为 base64 字符串并将其存储在文件中。对于 Java,这个问题中有几个选项,例如来自 apache 公共资源

如果您得到 byte[] 如其他答案所示,您可以通过执行

String imageString = new Base64().encodeBase64String(imageBytes);

以下操作来获取字符串并获取字节数组

byte[] imageBytes = new Base64().decodeBase64(imageString);

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 doing

String imageString = new Base64().encodeBase64String(imageBytes);

And get the byte array back with

byte[] imageBytes = new Base64().decodeBase64(imageString);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文