10
  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()
4

3 回答 3

9

您的读取解决方案基本上是两次读取字节,一次从文件中读取,一次从ByteArrayInputStream. 不要那样做

使用 Java 7 阅读

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

用 Java 7 编写

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

调用Files.newInputStream将返回ChannelInputStream未缓冲的(AFAIK)。你会想把它包起来

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

这样就可以减少对磁盘的 IO 调用,具体取决于您使用它的方式。

于 2013-08-29T23:15:18.787 回答
5

我参加聚会迟到了,但无论如何...

实际上,使用:

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

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

...可能会更快(尝试一下,使用探查器,以确保)。

这是因为这些变体在幕后使用RandomAccessFile-backed ImageInputStream/实现,而基于/的版本将默认使用磁盘支持的可搜索流实现。磁盘备份涉及将流的全部内容写入临时文件并可能从中读取(这是因为图像 I/O 通常受益于非线性数据访问)。ImageOutputStreamInputStreamOutputStream

如果您想在基于流的版本中避免额外的 I/O,以使用更多内存为代价,可以调用模棱两可的名称ImageIO.setUseCache(false)来禁用可搜索输入流的磁盘缓存。如果您正在处理非常大的图像,这显然不是一个好主意。

于 2013-08-30T13:42:31.153 回答
0

你几乎很适合写作。只是不要使用中间的 ByteArrayOutputStream。这是您代码中的一个巨大瓶颈。而是将 FileOutputStream 包装在 BufferedOutputStream 中并执行相同操作。

你的阅读也是如此。删除 Itermediate ByteArrayInputStream。

于 2013-08-29T23:14:14.417 回答