您好 我在内存中有一个 BufferedImage 实例,出于性能考虑,我想将其转换为 byte[] 编码为 base64 字符串,而无需 I/O 操作。我正在使用以下 API:
ByteArrayOutputStream baos = new ByteArrayOutputStream ();
ImageIO.write(image,"png",baos);
return baos.toByteArray();
但是这个API还是隐式的将镜像写入了OS的temp目录,当底层的OS temp目录满了无法创建temp文件的时候会导致失败。 堆栈跟踪:
Caused by: java.io.IOException: No space left on device
at java.io.RandomAccessFile.write(RandomAccessFile.java:493)
at javax.imageio.stream.FileCacheImageOutputStream.write(FileCacheImageOutputStream.java:134)
at javax.imageio.stream.ImageOutputStreamImpl.write(ImageOutputStreamImpl.java:66)
at com.sun.imageio.plugins.png.PNGImageWriter.write_magic(PNGImageWriter.java:376)
at com.sun.imageio.plugins.png.PNGImageWriter.write(PNGImageWriter.java:1115)
at javax.imageio.ImageWriter.write(ImageWriter.java:628)
at javax.imageio.ImageIO.write(ImageIO.java:1480)
at javax.imageio.ImageIO.write(ImageIO.java:1554)
是否有一种有效的(如内存中转换或有效的 I/O)方式来进行无 I/O 的转换?请指教。
最佳答案
通过 ImageIO.setUseCache() 禁用 ImageIO 缓存方法:
ImageIO.setUseCache(false);
根据 javadoc,它默认是开启的:
Sets a flag indicating whether a disk-based cache file should be used when creating ImageInputStreams and ImageOutputStreams.
When reading from a standard InputStream>, it may be necessary to save previously read information in a cache since the underlying stream does not allow data to be re-read. Similarly, when writing to a standard OutputStream, a cache may be used to allow a previously written value to be changed before flushing it to the final destination.
The cache may reside in main memory or on disk. Setting this flag to false disallows the use of disk for future streams, which may be advantageous when working with small images, as the overhead of creating and destroying files is removed.
On startup, the value is set to true.
关于java - 无需 I/O 将 BufferedImage 转换为 byte[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10235728/