将图像从文件读/写到 BufferedImage 的最快方法? [英] Fastest way to read/write Images from a File into a BufferedImage?
本文介绍了将图像从文件读/写到 BufferedImage 的最快方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
- 在 Java/Grails 中将图像从文件读取到 BufferedImage 的最快方法是什么?
- 在 Java/Grails 中将图像从 BufferedImage 写入文件的最快方法是什么?
我的变体(阅读):
byte [] imageByteArray = new File(basePath+imageSource).readBytes()
InputStream inStream = new ByteArrayInputStream(imageByteArray)
BufferedImage bufferedImage = ImageIO.read(inStream)
我的变体(写):
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()
推荐答案
您的读取解决方案基本上是读取字节两次,一次是从文件中读取,一次是从 ByteArrayInputStream
中读取.不要这样
Your solution to read is basically reading the bytes twice, once from the file and once from the ByteArrayInputStream
. Don't do that
用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) 没有被缓冲.你会想要包装它
The call to Files.newInputStream
will return a ChannelInputStream
which (AFAIK) is not buffered. You'll want to wrap it
new BufferedInputStream(Files.newInputStream(...));
减少对磁盘的 IO 调用,具体取决于您的使用方式.
So that there are less IO calls to disk, depending on how you use it.
这篇关于将图像从文件读/写到 BufferedImage 的最快方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文