加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 将BufferedImage转换为没有I / O的byte []

发布时间:2020-12-14 05:30:43 所属栏目:Java 来源:网络整理
导读:嗨,我在内存中有一个Buffered Image实例,并希望将其转换为byte []以编码为base64字符串,而不需要I / O操作来执行性能考虑.我正在使用以下API: ByteArrayOutputStream baos = new ByteArrayOutputStream ();ImageIO.write(image,"png",baos);return baos.toB
嗨,我在内存中有一个Buffered Image实例,并希望将其转换为byte []以编码为base64字符串,而不需要I / O操作来执行性能考虑.我正在使用以下API:
ByteArrayOutputStream baos = new ByteArrayOutputStream ();
ImageIO.write(image,"png",baos);
return baos.toByteArray();

但是,该API仍然将映像隐含地写入OS临时目录,这将导致在底层OS临时目录已满并且无法创建临时文件时出现故障.
堆栈跟踪:

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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读