1000字范文,内容丰富有趣,学习的好帮手!
1000字范文 > java image写入文件 从文件读取/写入图像到BufferedImage的最快方法?

java image写入文件 从文件读取/写入图像到BufferedImage的最快方法?

时间:2021-11-19 11:29:19

相关推荐

java image写入文件 从文件读取/写入图像到BufferedImage的最快方法?

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.

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。