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

user2722142 picture user2722142 · Aug 30, 2013 · Viewed 28.3k times · Source
  1. What is the fastest way to read Images from a File into a BufferedImage in Java/Grails?
  2. What is the fastest way to write Images from a BufferedImage into a File in Java/Grails?

my variant (read):

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

my variant (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()

Answer

Sotirios Delimanolis picture Sotirios Delimanolis · Aug 30, 2013

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.