简体   繁体   English

使用IOUtils和ImageIO编写图像文件有什么区别

[英]What is the difference between using IOUtils and ImageIO for writing an image file

I have a tiff image stored as Base64 encoded String in a file. 我有一个tiff图像存储为文件中的Base64编码字符串。 My aim is to create a tiff file out of it. 我的目标是从中创建一个tiff文件。 This is what I am doing: 这就是我在做的事情:

String base64encodedTiff = IOUtils.toString(new FileInputStream("C:/tiff-attachment.txt"));    
byte[] imgBytes = DatatypeConverter.parseBase64Binary(base64encodedTiff);
BufferedImage bufImg = ImageIO.read(new ByteArrayInputStream(imgBytes));   
ImageIO.write(bufImg, "tiff", new File("c:/new-darksouls-imageIO-tiff.tiff")); 

ImageIO.write() is throwing IllegalArgumentException because bufImg is null. ImageIO.write()抛出IllegalArgumentException因为bufImg为null。 I don't understand what am I doing wrong here. 我不明白我在这里做错了什么。

On the contrary if I use IOUtils to write, it works fine: 相反,如果我使用IOUtils写,它工作正常:

IOUtils.write(imgBytes, new FileOutputStream("c:/new-darksouls-io-tiff.tiff"));

Please help me understand 请帮我理解

  1. Why ImageIO is throwing exception 为什么ImageIO会抛出异常
  2. What is the right API and way for what I am trying to achieve. 什么是正确的API和我想要实现的方式。

ImageIO would be useful if, for example, you wanted to convert a PNG to a JPEG. 例如,如果要将PNG转换为JPEG,ImageIO将非常有用。 Since you don't need to manipulate the image or convert to another format, don't bother with ImageIO. 由于您不需要操作图像或转换为其他格式,因此请勿使用ImageIO。 Just use IOUtils.write() to save the TIFF data verbatim. 只需使用IOUtils.write()逐字保存TIFF数据。

ImageIO.read() is returning a null image because it can't read the TIFF file, probably because TIFF isn't one of the standard ImageIO plugin formats. ImageIO.read()返回一个空图像,因为它无法读取TIFF文件,可能是因为TIFF不是标准的ImageIO插件格式之一。 The standard supported image formats are listed here: 此处列出了标准支持的图像格式:

http://docs.oracle.com/javase/6/docs/api/javax/imageio/package-summary.html http://docs.oracle.com/javase/6/docs/api/javax/imageio/package-summary.html

An additional note -- the code you posted buffers the entire image in memory. 另外一个注意事项 - 您发布的代码将整个图像缓冲在内存中。 If you're concerned about using memory efficiently, consider using some kind of Base64 decoding input stream to perform the decoding on the fly. 如果您担心有效使用内存,请考虑使用某种Base64解码输入流来动态执行解码。 That might look like this: 这可能看起来像这样:

try (FileOutputStream out = new FileOutputStream("c:/new-darksouls-io-tiff.tiff");
     FileInputStream in = new FileInputStream("C:/tiff-attachment.txt");
     Base64InputStream decodedIn = new Base64InputStream(in)) {

    IOUtils.copy(decodedIn, out);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM