/** * Gets the size of an image. * * @param name the image name * @param in the input stream * @return the size of the image * * @throws BrokenImageException if the image is faulty * @throws UnrecognizedImageTypeException if the image type is unknown * @throws IOException if reading the image goes wrong */ public Dimension run(String name, InputStream in) throws IOException { final ImageInputStream stream = new MemoryCacheImageInputStream(in); final Iterator<ImageReader> i = ImageIO.getImageReaders(stream); if (!i.hasNext()) throw new UnrecognizedImageTypeException(name); final ImageReader reader = i.next(); try { reader.setInput(stream); return new Dimension(reader.getWidth(0), reader.getHeight(0)); } finally { reader.dispose(); } }
public ImageInputStream createInputStreamInstance(Object input, boolean useCache, File cacheDir) throws IOException { if (input instanceof InputStream) { InputStream is = (InputStream)input; if (useCache) { return new FileCacheImageInputStream(is, cacheDir); } else { return new MemoryCacheImageInputStream(is); } } else { throw new IllegalArgumentException(); } }
public static void main(String[] args) throws IOException { // Generate some trivial image and save it to a temporary array ByteArrayOutputStream tmp = new ByteArrayOutputStream(); ImageIO.write(new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB), "gif", tmp); // Read the stream ImageInputStream in = new MemoryCacheImageInputStream( new ByteArrayInputStream(tmp.toByteArray())); ImageReader reader = ImageIO.getImageReaders(in).next(); reader.setInput(in); // Retrieve standard image metadata tree IIOMetadata meta = reader.getImageMetadata(0); if (meta == null || !meta.isStandardMetadataFormatSupported()) { throw new Error("Test failure: Missing metadata"); } Element root = (Element) meta. getAsTree(IIOMetadataFormatImpl.standardMetadataFormatName); // Test getElementsByTagName("*") if (root.getElementsByTagName("*").getLength() == 0) { throw new RuntimeException("getElementsByTagName(\"*\") returns" + " nothing"); } }
/** * readBinaryMaskVolume() method * Reads volume-mask from a Binary file (1-byte character array) */ static public void readBinaryMaskVolume() { maskVolumeBoolean = new boolean [numberOfPValues]; FileInputStream fis; BufferedInputStream bis; try { fis = new FileInputStream(maskInputVolume); bis = new BufferedInputStream(fis); MemoryCacheImageInputStream mciis = new MemoryCacheImageInputStream(bis); setByteOrder(mciis, byteorder); for (int i=0; i < numberOfPValues; i++) { if (mciis.readUnsignedByte()>0) maskVolumeBoolean[i]=true; else maskVolumeBoolean[i]=false; } } catch (Exception e) { System.out.println("Error in readBinaryData(): "+e); } return; }
/** * Copy jpeg meta data (exif) from source to dest and save it to out * * @param source * @param dest * @param out * @throws IOException */ public static void copyJpegMetaData(InputStream source, InputStream dest, ImageOutputStream out) throws IOException { // Read meta data from src image Iterator iter = ImageIO.getImageReadersByFormatName("jpeg"); ImageReader reader=(ImageReader) iter.next(); ImageInputStream iis = new MemoryCacheImageInputStream(source); reader.setInput(iis); IIOMetadata metadata = reader.getImageMetadata(0); iis.close(); // Read dest image ImageInputStream outIis = new MemoryCacheImageInputStream(dest); reader.setInput(outIis); IIOImage image = reader.readAll(0,null); image.setMetadata(metadata); outIis.close(); // write dest image iter = ImageIO.getImageWritersByFormatName("jpeg"); ImageWriter writer=(ImageWriter) iter.next(); writer.setOutput(out); writer.write(image); }
/** Reads the image header. * Does nothing if the header has already been loaded. */ private void readHeader() throws IOException { if (image == null) { ImageReader r = new JPEGImageReader(getOriginatingProvider()); Object in = getInput(); if (in instanceof Buffer) { Buffer buffer = (Buffer) in; in=buffer.getData(); } if (in instanceof byte[]) { r.setInput(new MemoryCacheImageInputStream(AVIBMPDIB.prependDHTSeg((byte[]) in))); } else if (in instanceof ImageInputStream) { r.setInput(AVIBMPDIB.prependDHTSeg((ImageInputStream) in)); } else { r.setInput(AVIBMPDIB.prependDHTSeg((InputStream) in)); } image = r.read(0); } }
/** Reads the image header. * Does nothing if the header has already been loaded. */ private void readHeader() throws IOException { if (image == null) { ImageReader r = new JPEGImageReader(getOriginatingProvider()); Object in = getInput(); /*if (in instanceof Buffer) { Buffer buffer = (Buffer) in; in=buffer.getData(); }*/ if (in instanceof byte[]) { r.setInput(new MemoryCacheImageInputStream(AVIBMPDIB.prependDHTSeg((byte[]) in))); } else if (in instanceof ImageInputStream) { r.setInput(AVIBMPDIB.prependDHTSeg((ImageInputStream) in)); } else { r.setInput(AVIBMPDIB.prependDHTSeg((InputStream) in)); } image = r.read(0); } }
private static boolean isAcceptedImageFormat(final byte[] tileData) { if(tileData == null) { return false; } try(final ByteArrayInputStream byteArray = new ByteArrayInputStream(tileData); final MemoryCacheImageInputStream cacheImage = new MemoryCacheImageInputStream(byteArray)) { return TilesVerifier.canReadImage(pngImageReaders, cacheImage) || TilesVerifier.canReadImage(jpegImageReaders, cacheImage); } catch(final IOException ignored) { return false; } }
@Test public void checkJpegMaskRender() throws IOException, URISyntaxException { NitfRenderer renderer = new NitfRenderer(); // Mock up a render source ImageSegment mockImageSegment = Mockito.mock(ImageSegment.class); Mockito.when(mockImageSegment.getImageCompression()).thenReturn(ImageCompression.JPEGMASK); Mockito.when(mockImageSegment.getNumberOfBlocksPerRow()).thenReturn(2); Mockito.when(mockImageSegment.getNumberOfBlocksPerColumn()).thenReturn(3); Mockito.when(mockImageSegment.getNumberOfPixelsPerBlockHorizontal()).thenReturn(256L); Mockito.when(mockImageSegment.getNumberOfPixelsPerBlockVertical()).thenReturn(256L); Mockito.when(mockImageSegment.getNumBands()).thenReturn(1); ByteArrayOutputStream baos = new ByteArrayOutputStream(); baos.write(parseHexBinary("00000044000400000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000")); FileInputStream fis = new FileInputStream(new File(getClass().getResource("/256by256.jpg").toURI())); byte[] lastBlock = new byte[fis.available()]; fis.read(lastBlock); baos.write(lastBlock, 0, lastBlock.length); ImageInputStream iis = new MemoryCacheImageInputStream(new ByteArrayInputStream(baos.toByteArray())); Mockito.when(mockImageSegment.getData()).thenReturn(iis); BufferedImage imgAGRB = new BufferedImage((int) (mockImageSegment.getNumberOfBlocksPerRow() * mockImageSegment.getNumberOfPixelsPerBlockHorizontal()), (int) (mockImageSegment.getNumberOfBlocksPerColumn() * mockImageSegment.getNumberOfPixelsPerBlockVertical()), BufferedImage.TYPE_INT_ARGB); Graphics2D targetGraphic = imgAGRB.createGraphics(); renderer.render(mockImageSegment, targetGraphic); }
@Test public void checkJpegMaskRender2() throws IOException, URISyntaxException { NitfRenderer renderer = new NitfRenderer(); // Mock up a render source ImageSegment mockImageSegment = Mockito.mock(ImageSegment.class); Mockito.when(mockImageSegment.getImageCompression()).thenReturn(ImageCompression.JPEGMASK); Mockito.when(mockImageSegment.getNumberOfBlocksPerRow()).thenReturn(3); Mockito.when(mockImageSegment.getNumberOfBlocksPerColumn()).thenReturn(2); Mockito.when(mockImageSegment.getNumberOfPixelsPerBlockHorizontal()).thenReturn(256L); Mockito.when(mockImageSegment.getNumberOfPixelsPerBlockVertical()).thenReturn(256L); Mockito.when(mockImageSegment.getNumBands()).thenReturn(1); ByteArrayOutputStream baos = new ByteArrayOutputStream(); baos.write(parseHexBinary("00000044000400000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000")); FileInputStream fis = new FileInputStream(new File(getClass().getResource("/256by256.jpg").toURI())); byte[] lastBlock = new byte[fis.available()]; fis.read(lastBlock); baos.write(lastBlock, 0, lastBlock.length); ImageInputStream iis = new MemoryCacheImageInputStream(new ByteArrayInputStream(baos.toByteArray())); Mockito.when(mockImageSegment.getData()).thenReturn(iis); BufferedImage imgAGRB = new BufferedImage((int) (mockImageSegment.getNumberOfBlocksPerRow() * mockImageSegment.getNumberOfPixelsPerBlockHorizontal()), (int) (mockImageSegment.getNumberOfBlocksPerColumn() * mockImageSegment.getNumberOfPixelsPerBlockVertical()), BufferedImage.TYPE_INT_ARGB); Graphics2D targetGraphic = imgAGRB.createGraphics(); renderer.render(mockImageSegment, targetGraphic); }
/** * {@inheritDoc} */ @Override public final void handleGraphicSegment(final NitfReader reader, final long dataLength) throws NitfFormatException { GraphicSegmentParser graphicSegmentParser = new GraphicSegmentParser(); GraphicSegment graphicSegment = graphicSegmentParser.parse(reader, this, dataLength); if ((segmentsToExtract & GRAPHIC_DATA) == GRAPHIC_DATA) { if (dataLength > 0) { // TODO: [IMG-77] this implementation probably should have a file-backed option byte[] bytes = reader.readBytesRaw((int) dataLength); graphicSegment.setData(new MemoryCacheImageInputStream(new ByteArrayInputStream(bytes))); } } else { if (dataLength > 0) { reader.skip(dataLength); } } nitfStorage.getGraphicSegments().add(graphicSegment); }
/** * {@inheritDoc} */ @Override public final void handleSymbolSegment(final NitfReader reader, final long dataLength) throws NitfFormatException { SymbolSegmentParser symbolSegmentParser = new SymbolSegmentParser(); SymbolSegment symbolSegment = symbolSegmentParser.parse(reader, this, dataLength); if ((segmentsToExtract & SYMBOL_DATA) == SYMBOL_DATA) { if (dataLength > 0) { byte[] bytes = reader.readBytesRaw((int) dataLength); symbolSegment.setData(new MemoryCacheImageInputStream(new ByteArrayInputStream(bytes))); } } else { if (dataLength > 0) { reader.skip(dataLength); } } nitfStorage.getSymbolSegments().add(symbolSegment); }
@Test public void checkBadWriter() throws NitfFormatException { NitfReader reader = new NitfInputStreamReader(new BufferedInputStream(getInputStream("/WithBE.ntf"))); SlottedParseStrategy parseStrategy = new SlottedParseStrategy(SlottedParseStrategy.ALL_SEGMENT_DATA); HeapStrategyConfiguration heapStrategyConfiguration = new HeapStrategyConfiguration(length -> length > ABOUT_100K); HeapStrategy<ImageInputStream> imageDataStrategy = new ConfigurableHeapStrategy<>(heapStrategyConfiguration, file -> new FileImageInputStream(file), is -> new MemoryCacheImageInputStream(is)); parseStrategy.setImageHeapStrategy(imageDataStrategy); NitfParser.parse(reader, parseStrategy); // Introduce deliberate issue // Introduce deliberate issue ImageSegment imageSegment = parseStrategy.getDataSource().getImageSegments().get(0); TargetId originalTargetId = imageSegment.getImageTargetId(); TargetIdImpl newTargetId = new TargetIdImpl(); newTargetId.setBasicEncyclopediaNumber(originalTargetId.getBasicEncyclopediaNumber()); newTargetId.setOSuffix(originalTargetId.getOSuffix()); newTargetId.setCountryCode(null); imageSegment.setImageTargetId(newTargetId); NitfWriter writer = new NitfFileWriter(parseStrategy.getDataSource(), "checkBadWriter.ntf"); assertEquals(0, LOGGER.getLoggingEvents().size()); writer.write(); assertThat(LOGGER.getLoggingEvents(), is(Arrays.asList(LoggingEvent.error("Could not write", "Cannot generate string target identifier with null country code")))); }
@Test public void checkBadStreamWriter() throws NitfFormatException, FileNotFoundException { OutputStream outputStream = new FileOutputStream("checkBadStreamWriter.ntf"); NitfReader reader = new NitfInputStreamReader(new BufferedInputStream(getInputStream("/WithBE.ntf"))); SlottedParseStrategy parseStrategy = new SlottedParseStrategy(SlottedParseStrategy.ALL_SEGMENT_DATA); HeapStrategyConfiguration heapStrategyConfiguration = new HeapStrategyConfiguration(length -> length > ABOUT_100K); HeapStrategy<ImageInputStream> imageDataStrategy = new ConfigurableHeapStrategy<>(heapStrategyConfiguration, file -> new FileImageInputStream(file), is -> new MemoryCacheImageInputStream(is)); parseStrategy.setImageHeapStrategy(imageDataStrategy); NitfParser.parse(reader, parseStrategy); // Introduce deliberate issue ImageSegment imageSegment = parseStrategy.getDataSource().getImageSegments().get(0); TargetId originalTargetId = imageSegment.getImageTargetId(); TargetIdImpl newTargetId = new TargetIdImpl(); newTargetId.setBasicEncyclopediaNumber(originalTargetId.getBasicEncyclopediaNumber()); newTargetId.setOSuffix(originalTargetId.getOSuffix()); newTargetId.setCountryCode(null); imageSegment.setImageTargetId(newTargetId); NitfWriter writer = new NitfOutputStreamWriter(parseStrategy.getDataSource(), outputStream); assertEquals(0, LOGGER.getLoggingEvents().size()); writer.write(); assertThat(LOGGER.getLoggingEvents(), is(Arrays.asList(LoggingEvent.error("Could not write", "Cannot generate string target identifier with null country code")))); }
protected void roundTripFile(String sourceFileName) throws URISyntaxException, NitfFormatException, IOException { String outputFile = FilenameUtils.getName(sourceFileName); NitfReader reader = new NitfInputStreamReader(new BufferedInputStream(getInputStream(sourceFileName))); SlottedParseStrategy parseStrategy = new SlottedParseStrategy(SlottedParseStrategy.ALL_SEGMENT_DATA); HeapStrategyConfiguration heapStrategyConfiguration = new HeapStrategyConfiguration(length -> length > ABOUT_100K); HeapStrategy<ImageInputStream> imageDataStrategy = new ConfigurableHeapStrategy<>(heapStrategyConfiguration, file -> new FileImageInputStream(file), is -> new MemoryCacheImageInputStream(is)); parseStrategy.setImageHeapStrategy(imageDataStrategy); NitfParser.parse(reader, parseStrategy); NitfWriter writer = new NitfFileWriter(parseStrategy.getDataSource(), outputFile); writer.write(); assertTrue(FileUtils.contentEquals(new File(getClass().getResource(sourceFileName).toURI()), new File(outputFile))); assertTrue(new File(outputFile).delete()); // Do the same again, but with stream writing try ( OutputStream outputStream = new FileOutputStream(outputFile)) { writer = new NitfOutputStreamWriter(parseStrategy.getDataSource(), outputStream); writer.write(); assertTrue(FileUtils.contentEquals(new File(getClass().getResource(sourceFileName).toURI()), new File(outputFile))); } assertTrue(new File(outputFile).delete()); }
@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(). } }
@Test public void testCloseQuietlyImageInputStreamClosed() throws IOException { final ImageInputStream in = new MemoryCacheImageInputStream(new ClosedInputStream()); in.close(); IOUtils.closeQuietly(in); }
private ImageInputStream createImageInputStream(InputStream is) throws IOException { if (this.cacheDir != null) { return new FileCacheImageInputStream(is, cacheDir); } else { return new MemoryCacheImageInputStream(is); } }
/** * Reformats bit-discontiguous data into the {@code DataBuffer} * of the supplied {@code WritableRaster}. */ private static void reformatDiscontiguousData(byte[] buf, int[] bitsPerSample, int stride, int w, int h, WritableRaster raster) throws IOException { // Get SampleModel info. SampleModel sm = raster.getSampleModel(); int numBands = sm.getNumBands(); // Initialize input stream. ByteArrayInputStream is = new ByteArrayInputStream(buf); ImageInputStream iis = new MemoryCacheImageInputStream(is); // Reformat. long iisPosition = 0L; int y = raster.getMinY(); for(int j = 0; j < h; j++, y++) { iis.seek(iisPosition); int x = raster.getMinX(); for(int i = 0; i < w; i++, x++) { for(int b = 0; b < numBands; b++) { long bits = iis.readBits(bitsPerSample[b]); raster.setSample(x, y, b, (int)bits); } } iisPosition += stride; } }
public static void main(String[] args) throws IOException { // Generate some trivial image and save it to a temporary array ByteArrayOutputStream tmp = new ByteArrayOutputStream(); ImageIO.write(new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB), "gif", tmp); // Read it back in ImageInputStream in = new MemoryCacheImageInputStream( new ByteArrayInputStream(tmp.toByteArray())); ImageReader reader = ImageIO.getImageReaders(in).next(); reader.setInput(in); // Retrieve standard image metadata tree IIOMetadata meta = reader.getImageMetadata(0); if (meta == null || !meta.isStandardMetadataFormatSupported()) { throw new Error("Test failure: Missing metadata"); } Element root = (Element) meta. getAsTree(IIOMetadataFormatImpl.standardMetadataFormatName); NodeList nodeList = root. getElementsByTagName(root.getFirstChild().getNodeName()); /* * Accessing the nth node should return null and not throw * IndexOutOfBoundsException. */ Node n = (nodeList.item(nodeList.getLength())); }
public static void main(String args[]) throws Exception { Iterator<ImageReader> readers = ImageIO.getImageReadersBySuffix("simp"); ImageReader simpReader = null; if (readers.hasNext()) { simpReader = readers.next(); System.out.println("reader="+simpReader); } if (simpReader == null) { throw new RuntimeException("Reader not found."); } ImageReaderSpi spi = simpReader.getOriginatingProvider(); IIOMetadataFormat spiFmt = spi.getImageMetadataFormat("simp_metadata_1.0"); System.out.println("fmt from SPI=" + spiFmt); ByteArrayInputStream bais = new ByteArrayInputStream(simpData); ImageInputStream iis = new MemoryCacheImageInputStream(bais); simpReader.setInput(iis); BufferedImage bi = simpReader.read(0); System.out.println(bi); IIOMetadata metadata = simpReader.getImageMetadata(0); System.out.println("Image metadata="+metadata); IIOMetadataFormat format = metadata.getMetadataFormat("simp_metadata_1.0"); System.out.println("Image metadata format="+format); if (format == null) { throw new RuntimeException("MetadataFormat not found."); } }
/** * Reformats bit-discontiguous data into the {@code DataBuffer} * of the supplied {@code WritableRaster}. */ private static void reformatDiscontiguousData(byte[] buf, int stride, int w, int h, WritableRaster raster) throws IOException { // Get SampleModel info. SampleModel sm = raster.getSampleModel(); int numBands = sm.getNumBands(); int[] sampleSize = sm.getSampleSize(); // Initialize input stream. ByteArrayInputStream is = new ByteArrayInputStream(buf); ImageInputStream iis = new MemoryCacheImageInputStream(is); // Reformat. long iisPosition = 0L; int y = raster.getMinY(); for(int j = 0; j < h; j++, y++) { iis.seek(iisPosition); int x = raster.getMinX(); for(int i = 0; i < w; i++, x++) { for(int b = 0; b < numBands; b++) { long bits = iis.readBits(sampleSize[b]); raster.setSample(x, y, b, (int)bits); } } iisPosition += stride; } }