JAI是否过早关闭文件句柄?

时间:2016-07-18 19:41:34

标签: java garbage-collection jai

我正在使用JAI在java中读取Tiff文件。 使用此代码:

RenderedOp renderer = JAI.create("fileload", tifFilename);
return renderer.getAsBufferedImage();

使用java 7在一个盒子上工作正常,但在使用java 8的其他盒子上,得到这个:

Caused by: com.sun.media.jai.codecimpl.util.ImagingException
    at com.sun.media.jai.codecimpl.ImagingListenerProxy.errorOccurred(ImagingListenerProxy.java:63)
    at com.sun.media.jai.codecimpl.TIFFImage.getTile(TIFFImage.java:1087)
    at javax.media.jai.RenderedImageAdapter.getTile(RenderedImageAdapter.java:148)
    at javax.media.jai.NullOpImage.computeTile(NullOpImage.java:162)
    at com.sun.media.jai.util.SunTileScheduler.scheduleTile(SunTileScheduler.java:904)
    at javax.media.jai.OpImage.getTile(OpImage.java:1129)
    at javax.media.jai.PlanarImage.copyData(PlanarImage.java:2343)
    at javax.media.jai.RenderedImageAdapter.copyData(RenderedImageAdapter.java:163)
    at javax.media.jai.RenderedOp.copyData(RenderedOp.java:2299)
    at javax.media.jai.PlanarImage.getAsBufferedImage(PlanarImage.java:2525)
    at javax.media.jai.PlanarImage.getAsBufferedImage(PlanarImage.java:2546)
    at  ...
Caused by: com.sun.media.jai.codecimpl.util.ImagingException: IOException occured while reading TIFF image data.
    ... 17 more
Caused by: java.io.IOException: Stream Closed
    at java.io.RandomAccessFile.seek0(Native Method)
    at java.io.RandomAccessFile.seek(RandomAccessFile.java:557)
    at com.sun.media.jai.codec.FileSeekableStream.read(FileSeekableStream.java:168)
    at com.sun.media.jai.codec.SeekableStream.readFully(SeekableStream.java:318)
    at com.sun.media.jai.codecimpl.TIFFImage.getTile(TIFFImage.java:1081)
    ... 16 more

1 个答案:

答案 0 :(得分:1)

我的理论是垃圾收集正在进行并最终确定它不应该做的事情。很奇怪。用这个替换它:

try (SeekableStream seekableStream = new FileSeekableStream(filename)){
  TIFFDecodeParam param = null;
  ImageDecoder dec = ImageCodec.createImageDecoder("tiff", seekableStream, param);
  // convert to buffered image if desired
  return new RenderedImageAdapter(dec.decodeAsRenderedImage()).getAsBufferedImage(); // convert to buffered image
}

问题似乎消失了。我的猜测是因为FileSeekableStream s没有过早收集,因为它的句柄仍然在局部变量范围内。可能还有其他JAI方法可以做到这一点,只需确保在输入流上保留自己的句柄[?]

相关(帮助我发现这项工作:RenderedImage to BufferedImage for multipage-tiff reading

JAI create seems to leave file descriptors open

不确定是否也适用于其他图片格式