小编典典

JAI关闭文件句柄为时过早吗?

java

我正在使用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

阅读 309

收藏
2020-11-30

共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方法也可以做到这一点,只要确保在输入流上保留自己的句柄即可[?]

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

2020-11-30