Fastest way to read/write Images from a File into a BufferedImage?

て烟熏妆下的殇ゞ 提交于 2019-12-03 06:59:07

Your solution to read is basically reading the bytes twice, once from the file and once from the ByteArrayInputStream. Don't do that

With Java 7 to read

BufferedImage bufferedImage = ImageIO.read(Files.newInputStream(Paths.get(basePath + imageSource)));

With Java 7 to write

ImageIO.write(bufferedImage, "jpg", Files.newOutputStream(Paths.get(fullPath)));

The call to Files.newInputStream will return a ChannelInputStream which (AFAIK) is not buffered. You'll want to wrap it

new BufferedInputStream(Files.newInputStream(...));

So that there are less IO calls to disk, depending on how you use it.

I'm late to the party, but anyway...

Actually, using:

ImageIO.read(new File(basePath + imageSource));

and

ImageIO.write(bufferedImage, "jpeg", new File(fullPath));

...might prove faster (try it, using a profiler, to make sure).

This is because these variants use RandomAccessFile-backed ImageInputStream/ImageOutputStream implementations behind the scenes, while the InputStream/OutputStream-based versions will by default use a disk-backed seekable stream implementation. The disk-backing involves writing the entire contents of the stream to a temporary file and possibly reading back from it (this is because image I/O often benefits from non-linear data access).

If you want to avoid extra I/O with the stream based versions, at the cost of using more memory, it is possible to call the ambiguously named ImageIO.setUseCache(false), to disable disk caching of the seekable input streams. This is obviously not a good idea if you are dealing with very large images.

You are almost good for writing. Just don't use the intermediate ByteArrayOutputStream. It is a giant bottleneck in your code. Instead wrap the FileOutputStream in a BufferedOutputStream and do the same.

Same goes indeed for your reading. Remove the Itermediate ByteArrayInputStream.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!