从文件读取/写入图像到BufferedImage的最快方法? [英] Fastest way to read/write Images from a File into a BufferedImage?
本文介绍了从文件读取/写入图像到BufferedImage的最快方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
my variant(read):
byte []图像字节数组= (inStream)
我的变体(写):
BufferedImage bufferedImage = //某图像
def fullPath = //图像页面+文件名称
字节[] currentImage
尝试{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bufferedImage,jpg,baos);
baos.flush();
currentImage = baos.toByteArray();
baos.close();
} catch(IOException e){
System.out.println(e.getMessage());
$ b def newFile = new FileOutputStream(fullPath)
newFile.write(currentImage)
newFile.close()
解决方案
您的解决方案是基本读取两次字节从文件中,一次从 ByteArrayInputStream
。不要这样做
使用Java 7读取
BufferedImage bufferedImage = ImageIO.read(Files.newInputStream(Paths.get(basePath + imageSource)));
使用Java 7编写
<$ p $ ImageIO.write(bufferedImage,jpg,Files.newOutputStream(Paths.get(fullPath)));
调用 Files.newInputStream
将会返回一个 ChannelInputStream
其中(AFAIK)未被缓冲。你需要包装它
new BufferedInputStream(Files.newInputStream(...));
这样可以减少对磁盘的IO调用,具体取决于您如何使用它。
- What is the fastest way to read Images from a File into a BufferedImage in Java/Grails?
- 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()
解决方案
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.
这篇关于从文件读取/写入图像到BufferedImage的最快方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文