Fastest way to read / write images from a file in BufferedImage?

  • What is the fastest way to read images from a file in BufferedImage in Java / Grails?
  • What is the fastest way to write images from a BufferedImage to a file in Java / Grails?

my option (read):

byte [] imageByteArray = new File(basePath+imageSource).readBytes() InputStream inStream = new ByteArrayInputStream(imageByteArray) BufferedImage bufferedImage = ImageIO.read(inStream) 

my option (write):

 BufferedImage bufferedImage = // some image def fullPath = // image page + file name byte [] currentImage try{ ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write( bufferedImage, "jpg", baos ); baos.flush(); currentImage = baos.toByteArray(); baos.close(); }catch(IOException e){ System.out.println(e.getMessage()); } } def newFile = new FileOutputStream(fullPath) newFile.write(currentImage) newFile.close() 
+7
java grails javax.imageio
source share
3 answers

Your reading solution basically reads bytes twice, once from a file and once from ByteArrayInputStream . Do not do this

With Java 7 for reading

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

From Java 7 to write

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

A call to Files.newInputStream returns a ChannelInputStream that (AFAIK) is not buffered. You will want to wrap it

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

So there are fewer IO calls on the disk, depending on how you use it.

+6
source share

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

Actually, using:

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

and

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

... might turn out to be faster (try using the profiler to make sure).

This is because these options use RandomAccessFile -backed ImageInputStream / ImageOutputStream implementations behind the scenes, and versions with InputStream / OutputStream support will use the search stream implementation with disk support by default. Backing up a disk involves writing the entire contents of a stream to a temporary file and possibly reading it (this is because image input / output operations often benefit from non-linear data access).

If you want to avoid additional input-output operations with streaming versions, due to the use of more memory, you can call the ambiguously named ImageIO.setUseCache(false) to disable caching of input search streams. This, of course, is not a good idea if you are dealing with very large images.

+5
source share

You are almost ready to write. Just don't use an intermediate ByteArrayOutputStream. This is a giant bottleneck in your code. Instead, wrap FileOutputStream in BufferedOutputStream and do the same.

The same thing happens for your reading. Remove Itermediate ByteArrayInputStream.

0
source share

All Articles