@Override public Raster readRaster(int frameIndex, ImageReadParam param) throws IOException { readMetadata(); checkIndex(frameIndex); if (decompressor != null) { decompressor.setInput(iisOfFrame(frameIndex)); if (LOG.isDebugEnabled()) LOG.debug("Start decompressing frame #" + (frameIndex + 1)); Raster wr = pmi.decompress() == pmi && decompressor.canReadRaster() ? decompressor.readRaster(0, decompressParam(param)) : decompressor.read(0, decompressParam(param)).getRaster(); if (LOG.isDebugEnabled()) LOG.debug("Finished decompressing frame #" + (frameIndex + 1)); return wr; } iis.seek(pixeldata.offset + frameIndex * frameLength); WritableRaster wr = Raster.createWritableRaster(createSampleModel(dataType, banded), null); DataBuffer buf = wr.getDataBuffer(); if (buf instanceof DataBufferByte) { byte[][] data = ((DataBufferByte) buf).getBankData(); for (byte[] bs : data) iis.readFully(bs); if (pixeldata.bigEndian && pixeldataVR.vr == VR.OW) ByteUtils.swapShorts(data); } else { short[] data = ((DataBufferUShort) buf).getData(); iis.readFully(data, 0, data.length); } return wr; }
@Override public Directory read(final ImageInputStream input) throws IOException { Validate.notNull(input, "input"); List<PSDEntry> entries = new ArrayList<PSDEntry>(); while (true) { try { int type = input.readInt(); if (type != PSD.RESOURCE_TYPE) { throw new IIOException( String.format("Wrong image resource type, expected '8BIM': '%08x'", type)); } short id = input.readShort(); PSDResource resource = new PSDResource(id, input); entries.add(new PSDEntry(id, resource.name(), resource.data())); } catch (EOFException e) { break; } } return new PSDDirectory(entries); }
private Dimension getSize(File file) { try { ImageInputStream input = ImageIO.createImageInputStream(file); if (input != null) { try { Iterator<ImageReader> readers = ImageIO.getImageReaders(input); if (readers.hasNext()) { ImageReader reader = readers.next(); try { reader.setInput(input); return new Dimension(reader.getWidth(0), reader.getHeight(0)); } finally { reader.dispose(); } } } finally { if (input != null) { input.close(); } } } // Fallback: read the image using the normal means BufferedImage image = ImageIO.read(file); if (image != null) { return new Dimension(image.getWidth(), image.getHeight()); } else { return null; } } catch (IOException e) { // Pass -- we can't handle all image types, warn about those we can return null; } }
public Dimension getImageDimensions(InputStream imageStream) { ImageInputStream in = null; Dimension dimension = null; try { in = ImageIO.createImageInputStream(imageStream); final Iterator<ImageReader> readers = ImageIO.getImageReaders(in); if (readers.hasNext()) { ImageReader reader = readers.next(); try { reader.setInput(in); dimension = new Dimension(reader.getWidth(0), reader.getHeight(0)); } finally { reader.dispose(); } } } catch (IOException e) { e.printStackTrace(); } finally { if (in != null) try { in.close(); } catch (Exception e) { e.printStackTrace(); } } return dimension; }
private BufferedImage getImage(File file) { ImageInputStream iis = null; BufferedImage image = null; try { iis = ImageIO.createImageInputStream(file); Iterator<ImageReader> it = ImageIO.getImageReaders(iis); if (!it.hasNext()) throw new UnsupportedOperationException("No image reader fround."); ImageReader reader = it.next(); reader.setInput(iis); int scaleFactor; if (reader.getWidth(0) >= reader.getHeight(0)) scaleFactor = Math.round(((float) reader.getWidth(0)) / MAX_SIZE); else scaleFactor = Math.round(((float) reader.getHeight(0)) / MAX_SIZE); ImageReadParam param = reader.getDefaultReadParam(); param.setSourceSubsampling(scaleFactor, scaleFactor, 0, 0); image = reader.read(0, param); } catch (IOException e) { e.printStackTrace(); } finally { if (iis != null) try { iis.close(); } catch (IOException e) { e.printStackTrace(); } } return image; }
private void parseProperties() throws IOException { String line; stream.seek(0); propertiesByteSize = 0; long posInStream = 0l; while ((line = stream.readLine()) != null) { if (!line.startsWith("#")) { stream.seek(posInStream); break; } propertiesByteSize += (stream.getStreamPosition() - posInStream); posInStream = stream.getStreamPosition(); line = line.substring(1); int pos = line.indexOf('='); if (pos == -1) { throw new IOException("Missing '=' in '" + line + "'"); } String name = line.substring(0, pos).trim(); if (name.isEmpty()) { throw new IOException("Empty property name in '" + line + "'"); } String value = line.substring(pos + 1).trim(); try { if (contains(Constants.CRS_IDENTIFIERS, name) && crs != null) { crs = CRS.parseWKT(value); } } catch (FactoryException e) { throw new IOException(e); } properties.put(name, value); } propertiesParsed = true; }
@Override public BufferedImage read(Class<? extends BufferedImage> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { ImageInputStream imageInputStream = null; ImageReader imageReader = null; try { imageInputStream = createImageInputStream(inputMessage.getBody()); MediaType contentType = inputMessage.getHeaders().getContentType(); Iterator<ImageReader> imageReaders = ImageIO.getImageReadersByMIMEType(contentType.toString()); if (imageReaders.hasNext()) { imageReader = imageReaders.next(); ImageReadParam irp = imageReader.getDefaultReadParam(); process(irp); imageReader.setInput(imageInputStream, true); return imageReader.read(0, irp); } else { throw new HttpMessageNotReadableException( "Could not find javax.imageio.ImageReader for Content-Type [" + contentType + "]"); } } finally { if (imageReader != null) { imageReader.dispose(); } if (imageInputStream != null) { try { imageInputStream.close(); } catch (IOException ex) { // ignore } } } }
public boolean canDecodeInput(Object input) throws IOException { // The input source must be an ImageInputStream because the constructor // passes STANDARD_INPUT_TYPE (an array consisting of ImageInputStream) // as the only type of input source that it will deal with to its // superclass. if (!(input instanceof ImageInputStream)) return false; ImageInputStream stream = (ImageInputStream) input; /** Read and validate the input source's header. */ byte[] header = new byte[8]; try { // The input source's current position must be preserved so that // other ImageReaderSpis can determine if they can decode the input // source's format, should this input source be unable to handle the // decoding. Because the input source is an ImageInputStream, its // mark() and reset() methods are called to preserve the current // position. stream.mark(); stream.read(header); stream.reset(); } catch (IOException e) { return false; } byte[] controlHeader = new byte[] {(byte) 151, 74, 66, 50, 13, 10, 26, 10}; return Arrays.equals(controlHeader, header); }
@Test public void testCloseQuietlyImageInputStreamClosed() throws IOException { final ImageInputStream in = new MemoryCacheImageInputStream(new ClosedInputStream()); in.close(); IOUtils.closeQuietly(in); }
private int locateImage(int imageIndex) throws IIOException { readHeader(); try { // Find closest known index int index = Math.min(imageIndex, imageStartPosition.size() - 1); // Seek to that position Long l = (Long) imageStartPosition.get(index); stream.seek(l.longValue()); // Skip IFDs until at desired index or last image found while (index < imageIndex) { int count = stream.readUnsignedShort(); stream.skipBytes(12 * count); long offset = stream.readUnsignedInt(); if (offset == 0) { return index; } imageStartPosition.add(new Long(offset)); stream.seek(offset); ++index; } } catch (IOException e) { throw new IIOException("Couldn't seek!", e); } if (currIndex != imageIndex) { imageMetadata = null; } currIndex = imageIndex; return imageIndex; }
@Test public void testAddAndGetTile() throws InterruptedException, FileNotFoundException, IOException { // Input stream to use ImageInputStream stream_in = null; try { stream_in = new FileImageInputStream(TestData.file(this, "world.tiff")); // Input RenderedImage to use final RenderedOp input = ImageReadDescriptor.create( stream_in, 0, false, false, false, null, null, null, null, null); // Boolean used for checking if the conditions are passed final AtomicBoolean passed = new AtomicBoolean(true); // Cache creation final ConcurrentTileCacheMultiMap cache = new ConcurrentTileCacheMultiMap(1000 * 1000, false, 1f, 4); // Selection of one tile from the image Raster data = input.getTile(input.getMinTileX(), input.getMinTileY()); // Setting the tile inside the cache cache.add(input, input.getMinTileX(), input.getMinTileY(), data); // Thread pool to use for doing concurrent access on the cache ThreadPoolExecutor executor = new ThreadPoolExecutor( TOTAL, TOTAL, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(1000000)); // Latch used for waiting all the threads to end their work final CountDownLatch latch = new CountDownLatch(TOTAL); // Cycle for launching various requests int counter = TOTAL; while (counter > 0) { executor.execute( new Runnable() { public void run() { // Get the tile to use Raster data = cache.getTile(input, input.getMinTileX(), input.getMinTileY()); if (data == null) { passed.getAndSet(false); } latch.countDown(); } }); // Counter update counter--; } // Waiting all threads to finish latch.await(); // Ensure that all the threads have found the tile Assert.assertTrue(passed.get()); } finally { try { if (stream_in != null) { stream_in.flush(); stream_in.close(); } } catch (Throwable t) { // } } }
private static Dimension getSizeUsingImageIO(URL url) throws IOException { InputStream in = null; ImageInputStream iis = null; ImageReader reader = null; try { in = url.openStream(); iis = new MemoryCacheImageInputStream(in); Iterator<ImageReader> it = ImageIO.getImageReaders(iis); if (!it.hasNext()) return null; reader = it.next(); reader.setInput(iis, true, true); Dimension d = new Dimension(reader.getWidth(0), reader.getHeight(0)); if (d.width <= 0 || d.height <= 0) throw new RuntimeException("invalid dimensions: " + d.width + "x" + d.height); return d; } finally { try { if (reader != null) reader.dispose(); } catch (Exception e) { e.printStackTrace(); } try { if (iis != null) iis.close(); } catch (Exception e) { e.printStackTrace(); } try { if (in != null) in.close(); } catch (Exception e) { e.printStackTrace(); } } }
/** * reads an AOT Kx LUT (BBDR breadboard procedure GA_read_LUT_AOD) * * <p>A LUT value can be accessed with lut.getValue(new double[]{wvlValue, aotValue, hsfValue, * aziValue, szaValue, vzaValue, parameterValue}); * * @param sensor The sensor * @return LookupTable * @throws java.io.IOException when failing to real LUT data */ public static LookupTable getAotKxLookupTable(Sensor sensor) throws IOException { ImageInputStream iis = Luts.getAotKxLutData(sensor.getInstrument()); try { // read LUT dimensions and values float[] vza = Luts.readDimension(iis); int nVza = vza.length; float[] sza = Luts.readDimension(iis); int nSza = sza.length; float[] azi = Luts.readDimension(iis); int nAzi = azi.length; float[] hsf = Luts.readDimension(iis); int nHsf = hsf.length; float[] aot = Luts.readDimension(iis); int nAot = aot.length; float[] kx = new float[] {1.0f, 2.0f}; int nKx = kx.length; float[] wvl = sensor.getWavelength(); final int nWvl = wvl.length; float[] lut = new float[nKx * nVza * nSza * nAzi * nHsf * nAot * nWvl]; iis.readFully(lut, 0, lut.length); return new LookupTable(lut, wvl, aot, hsf, azi, sza, vza, kx); } finally { iis.close(); } }
/** * Gets a list of <code>IIOImage</code> objects for an image file. * * @param imageFile input image file. It can be any of the supported formats, including TIFF, * JPEG, GIF, PNG, BMP, JPEG, and PDF if GPL Ghostscript is installed * @return a list of <code>IIOImage</code> objects * @throws Exception */ public static List<IIOImage> getIIOImageList(File imageFile) throws IOException { File workingTiffFile = null; ImageReader reader = null; ImageInputStream iis = null; try { // convert PDF to TIFF if (imageFile.getName().toLowerCase().endsWith(".pdf")) { workingTiffFile = PdfUtilities.convertPdf2Tiff(imageFile); imageFile = workingTiffFile; } List<IIOImage> iioImageList = new ArrayList<IIOImage>(); String imageFileName = imageFile.getName(); String imageFormat = imageFileName.substring(imageFileName.lastIndexOf('.') + 1); if (imageFormat.matches("(pbm|pgm|ppm)")) { imageFormat = "pnm"; } else if (imageFormat.equals("jp2")) { imageFormat = "jpeg2000"; } Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(imageFormat); reader = readers.next(); if (reader == null) { throw new RuntimeException( "Need to install JAI Image I/O package.\nhttps://jai-imageio.dev.java.net"); } iis = ImageIO.createImageInputStream(imageFile); reader.setInput(iis); int imageTotal = reader.getNumImages(true); for (int i = 0; i < imageTotal; i++) { // IIOImage oimage = new IIOImage(reader.read(i), null, // reader.getImageMetadata(i)); IIOImage oimage = reader.readAll(i, reader.getDefaultReadParam()); iioImageList.add(oimage); } return iioImageList; } finally { try { if (iis != null) { iis.close(); } if (reader != null) { reader.dispose(); } } catch (Exception e) { // ignore } if (workingTiffFile != null && workingTiffFile.exists()) { workingTiffFile.delete(); } } }
GranuleOverviewLevelDescriptor getLevel(final int index) { // load level // create the base grid to world transformation ImageInputStream inStream = null; ImageReader reader = null; try { // get a stream assert cachedStreamSPI != null : "no cachedStreamSPI available!"; inStream = cachedStreamSPI.createInputStreamInstance( granuleUrl, ImageIO.getUseCache(), ImageIO.getCacheDirectory()); if (inStream == null) throw new IllegalArgumentException( "Unable to create an inputstream for the granuleurl:" + (granuleUrl != null ? granuleUrl : "null")); // get a reader and try to cache the relevant SPI if (cachedReaderSPI == null) { reader = ImageIOExt.getImageioReader(inStream); if (reader != null) cachedReaderSPI = reader.getOriginatingProvider(); } else reader = cachedReaderSPI.createReaderInstance(); if (reader == null) throw new IllegalArgumentException( "Unable to get an ImageReader for the provided file " + granuleUrl.toString()); reader.setInput(inStream); // call internal method which will close everything return getLevel(index, reader); } catch (IllegalStateException e) { // clean up try { if (inStream != null) inStream.close(); } catch (Throwable ee) { } finally { if (reader != null) reader.dispose(); } throw new IllegalArgumentException(e); } catch (IOException e) { // clean up try { if (inStream != null) inStream.close(); } catch (Throwable ee) { } finally { if (reader != null) reader.dispose(); } throw new IllegalArgumentException(e); } }
/** * Write world image extensions : TFW, PRJ, TAB * * @param request * @param file * @param in * @throws IOException */ private void writeWorldImageExt(WcsReaderRequest request, File file) throws IOException { String baseFilePath = file.getPath().substring(0, file.getPath().lastIndexOf('.')); // Compute image size and image transformed BBOX ReferencedEnvelope transformedBBox; AffineTransform transform; int width = -1; int height = -1; String ext = FileUtils.extension(file); try { final Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(ext.substring(1)); while (readers.hasNext() && width < 0 && height < 0) { ImageInputStream stream = null; try { ImageReader reader = readers.next(); stream = ImageIO.createImageInputStream(file.getAbsoluteFile()); reader.setInput(stream, true, false); width = reader.getWidth(0); height = reader.getHeight(0); break; } catch (Exception e) { width = -1; height = -1; // try next reader; } finally { if (stream != null) { stream.close(); } } } transformedBBox = request.requestBbox.transform(request.responseCRS, true, 10); if (width < 0) { width = (int) Math.round(transformedBBox.getWidth() / request.crsResolution()); } if (height < 0) { height = (int) Math.round(transformedBBox.getHeight() / request.crsResolution()); } Rectangle imageSize = new Rectangle(width, height); transform = RendererUtilities.worldToScreenTransform(transformedBBox, imageSize); transform.invert(); } catch (Exception e) { throw new ExtractorException(e); } // Generate TFW TAB PRJ files createWorldFile(transform, ext, baseFilePath); createTABFile(transformedBBox, width, height, baseFilePath, ext); createPrjFile(request.responseCRS, baseFilePath); }
/** * {@inheritDoc} * * @return GridCoverageReader. */ @Override public GridCoverageReader convert(final ReferenceType source, final Map<String, Object> params) throws UnconvertibleObjectException { final InputStream stream = getInputStreamFromReference(source); String encoding = null; if (params != null && params.get(ENCODING) != null) { encoding = (String) params.get(ENCODING); } ImageInputStream imageStream = null; try { // decode form base64 stream if (encoding != null && encoding.equals(WPSEncoding.BASE64.getValue())) { final String encodedImage = IOUtilities.toString(stream); final byte[] byteData = Base64.decode(encodedImage.trim()); if (byteData != null && byteData.length > 0) { try (InputStream is = new ByteArrayInputStream(byteData)) { imageStream = ImageIO.createImageInputStream(is); } } } else { imageStream = ImageIO.createImageInputStream(stream); } if (imageStream != null) { final ImageReader reader; if (source.getMimeType() != null) { reader = XImageIO.getReaderByMIMEType(source.getMimeType(), imageStream, null, null); } else { reader = XImageIO.getReader(imageStream, null, Boolean.FALSE); } return CoverageIO.createSimpleReader(reader); } else { throw new UnconvertibleObjectException("Error during image stream acquisition."); } } catch (MalformedURLException ex) { throw new UnconvertibleObjectException( "Reference grid coverage invalid input : Malformed url", ex); } catch (CoverageStoreException ex) { throw new UnconvertibleObjectException( "Reference grid coverage invalid input : Can't read coverage", ex); } catch (IOException ex) { throw new UnconvertibleObjectException("Reference grid coverage invalid input : IO", ex); } finally { if (imageStream != null) { try { imageStream.close(); } catch (IOException ex) { LOGGER.log(Level.WARNING, "Error during release the image stream.", ex); } } } }
/** * Returns the geotiff metadata for this geotiff file. * * @return the metadata */ public GeoTiffIIOMetadataDecoder getMetadata() { GeoTiffIIOMetadataDecoder metadata = null; ImageReader reader = null; boolean closeMe = true; ImageInputStream stream = null; try { if ((source instanceof InputStream) || (source instanceof ImageInputStream)) { closeMe = false; } if (source instanceof ImageInputStream) { stream = (ImageInputStream) source; } else { inStreamSPI = ImageIOExt.getImageInputStreamSPI(source); if (inStreamSPI == null) { throw new IllegalArgumentException("No input stream for the provided source"); } stream = inStreamSPI.createInputStreamInstance( source, ImageIO.getUseCache(), ImageIO.getCacheDirectory()); } if (stream == null) { throw new IllegalArgumentException("No input stream for the provided source"); } stream.mark(); reader = READER_SPI.createReaderInstance(); reader.setInput(stream); final IIOMetadata iioMetadata = reader.getImageMetadata(0); metadata = new GeoTiffIIOMetadataDecoder(iioMetadata); } catch (IOException e) { if (LOGGER.isLoggable(Level.SEVERE)) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } } finally { if (reader != null) try { reader.dispose(); } catch (Throwable t) { } if (stream != null) { try { stream.reset(); } catch (Throwable t) { } if (closeMe) { try { stream.close(); } catch (Throwable t) { } } } } return metadata; }
// TODO: Candidate util method private static long skipToEOF(final ImageInputStream stream) throws IOException { long length = stream.length(); if (length > 0) { // Known length, skip there and we're done. stream.seek(length); } else { // Otherwise, seek to EOF the hard way. // First, store stream position... long pos = stream.getStreamPosition(); // ...skip 1k blocks until we're passed EOF... while (stream.skipBytes(1024l) > 0) { if (stream.read() == -1) { break; } pos = stream.getStreamPosition(); } // ...go back to last known pos... stream.seek(pos); // ...finally seek until EOF one byte at a time. Done. while (stream.read() != -1) {} } return stream.getStreamPosition(); }
BufferedImage getThumbnail(ImageInputStream iis, JPEGImageReader reader) throws IOException { iis.mark(); iis.seek(streamPos); JPEGImageReader thumbReader = new JPEGImageReader(null); thumbReader.setInput(iis); thumbReader.addIIOReadProgressListener(new ThumbnailReadListener(reader)); BufferedImage ret = thumbReader.read(0, null); thumbReader.dispose(); iis.reset(); return ret; }
public BufferedImage getBufferedImage(String keepLetter) { try { final InputStream is = getInputStream(keepLetter); final ImageInputStream iis = ImageIO.createImageInputStream(is); final VP8Decoder vp8Decoder = new VP8Decoder(); vp8Decoder.decodeFrame(iis, false); iis.close(); return vp8Decoder.getFrame().getBufferedImage(); } catch (Exception e) { return null; } }
public void runTest(Object ctx, int numReps) { final Context ictx = (Context) ctx; try { do { ImageInputStream iis = ictx.createImageInputStream(); iis.close(); ictx.closeOriginalStream(); } while (--numReps >= 0); } catch (IOException e) { e.printStackTrace(); } }
private void initBoolDecoder() throws IOException { value = 0; /* value = first 16 input bits */ data.seek(offset); value = data.readUnsignedByte() << 8; // value = (data[offset]) << 8; offset++; range = 255; /* initial range is full */ bit_count = 0; /* have not yet shifted out any bits */ }
@Test public void testCloseQuietlyImageInputStreamOpen() { final ImageInputStream in = new MemoryCacheImageInputStream(new NullInputStream(1000)); IOUtils.closeQuietly(in); try { in.close(); fail(); } catch (IOException e) { // This, oddly, the expected behavior of close(). } }
public boolean canDecodeInput(Object source) throws IOException { if (!(source instanceof ImageInputStream)) { return false; } ImageInputStream stream = (ImageInputStream) source; byte[] b = new byte[2]; stream.mark(); stream.readFully(b); stream.reset(); return (b[0] == 0x42) && (b[1] == 0x4d); }
private void skipToLine(long lineOffset) throws IOException { if (bytePositionForOffset.containsKey(lineOffset)) { stream.seek(bytePositionForOffset.get(lineOffset)); return; } Map.Entry<Long, Long> entry = getBestOffset(lineOffset); stream.seek(entry.getValue()); long linesToSkip = lineOffset - entry.getKey(); for (int i = 0; i < linesToSkip; i++) { stream.readLine(); } bytePositionForOffset.put(lineOffset, stream.getStreamPosition()); }
BufferedImage getThumbnail(ImageInputStream iis, JPEGImageReader reader) throws IOException { iis.mark(); iis.seek(streamPos); DataBufferByte buffer = new DataBufferByte(getLength()); readByteBuffer(iis, buffer.getData(), reader, 1.0F, 0.0F); iis.reset(); WritableRaster raster = Raster.createInterleavedRaster( buffer, thumbWidth, thumbHeight, thumbWidth * 3, 3, new int[] {0, 1, 2}, null); ColorModel cm = new ComponentColorModel( JPEG.JCS.sRGB, false, false, ColorModel.OPAQUE, DataBuffer.TYPE_BYTE); return new BufferedImage(cm, raster, false, null); }
/** * Load image data for file and put user data attributes into file. * * @param file File * @return true if file image is loaded. * @throws java.io.IOException if image can not be loaded */ private static boolean refresh(@NotNull VirtualFile file) throws IOException { Long loadedTimeStamp = file.getUserData(TIMESTAMP_KEY); SoftReference<BufferedImage> imageRef = file.getUserData(BUFFERED_IMAGE_REF_KEY); if (loadedTimeStamp == null || loadedTimeStamp.longValue() != file.getTimeStamp() || SoftReference.dereference(imageRef) == null) { try { final byte[] content = file.contentsToByteArray(); if (ICO_FORMAT.equalsIgnoreCase(file.getExtension())) { try { final BufferedImage image = ICO_IMAGE_PARSER.getBufferedImage(new ByteSourceArray(content), null); file.putUserData(FORMAT_KEY, ICO_FORMAT); file.putUserData(BUFFERED_IMAGE_REF_KEY, new SoftReference<>(image)); return true; } catch (ImageReadException ignore) { } } InputStream inputStream = new ByteArrayInputStream(content, 0, content.length); ImageInputStream imageInputStream = ImageIO.createImageInputStream(inputStream); try { Iterator<ImageReader> imageReaders = ImageIO.getImageReaders(imageInputStream); if (imageReaders.hasNext()) { ImageReader imageReader = imageReaders.next(); try { file.putUserData(FORMAT_KEY, imageReader.getFormatName()); ImageReadParam param = imageReader.getDefaultReadParam(); imageReader.setInput(imageInputStream, true, true); int minIndex = imageReader.getMinIndex(); BufferedImage image = imageReader.read(minIndex, param); file.putUserData(BUFFERED_IMAGE_REF_KEY, new SoftReference<>(image)); return true; } finally { imageReader.dispose(); } } } finally { imageInputStream.close(); } } finally { // We perform loading no more needed file.putUserData(TIMESTAMP_KEY, file.getTimeStamp()); } } return false; }
public BufferedImage decode(ImageInputStream in) throws IOException, BMPException { if (!useDefaultMasks) bitmasks = readBitMasks(in); skipToImage(in); Dimension d = infoHeader.getSize(); int h = (int) d.getHeight(); int w = (int) d.getWidth(); // BMP scanlines are padded to dword offsets int scansize = (w + (w & 1)) << 1; short[] data = new short[w * h]; for (int y = h - 1; y >= 0; y--) { byte[] scanline = new byte[scansize]; if (in.read(scanline) != scansize) throw new IOException("Couldn't read image data."); for (int x = 0; x < w; x++) data[x + y * w] = (short) ((scanline[x * 2] & (0xFF)) | ((scanline[x * 2 + 1] & (0xFF)) << 8)); } ColorModel cm = new DirectColorModel(16, bitmasks[0], bitmasks[1], bitmasks[2]); SampleModel sm = new SinglePixelPackedSampleModel(DataBuffer.TYPE_USHORT, w, h, bitmasks); DataBuffer db = new DataBufferUShort(data, w * h, 0); WritableRaster raster = Raster.createWritableRaster(sm, db, null); return new BufferedImage(cm, raster, false, null); }
@Override public void close() { try { stream.close(); } catch (IOException ignore) { } }