List of usage examples for javax.imageio.stream FileImageInputStream FileImageInputStream
public FileImageInputStream(RandomAccessFile raf)
From source file:org.codice.imaging.nitf.core.AbstractWriterTest.java
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();//from w w w . j a va2 s . c o m 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()); }
From source file:org.dcm4che2.tool.dcm2dcm.Dcm2Dcm.java
/** * Recodes the images from the source transfer syntax, as read from the src * file, to the specified destination syntax. *//*from w w w.j a v a 2s .c o m*/ public void recodeImages(File src, File dest) throws IOException { ImageReader reader = new DicomImageReaderSpi().createReaderInstance(); ImageWriter writer = new DicomImageWriterSpi().createWriterInstance(); DicomStreamMetaData writeMeta = (DicomStreamMetaData) writer.getDefaultStreamMetadata(null); DicomObject ds; int frames; FileImageOutputStream output = null; try { FileImageInputStream input = new FileImageInputStream(src); try { reader.setInput(input); if (dest.exists()) dest.delete(); output = new FileImageOutputStream(dest); writer.setOutput(output); DicomStreamMetaData streamMeta = (DicomStreamMetaData) reader.getStreamMetadata(); ds = streamMeta.getDicomObject(); DicomObject newDs = new BasicDicomObject(); ds.copyTo(newDs); writeMeta.setDicomObject(newDs); frames = ds.getInt(Tag.NumberOfFrames, 1); newDs.putString(Tag.TransferSyntaxUID, VR.UI, destinationSyntax.uid()); newDs.putString(Tag.ImplementationClassUID, VR.UI, Implementation.classUID()); newDs.putString(Tag.ImplementationVersionName, VR.SH, Implementation.versionName()); if (overwriteObject != null) { overwriteObject.copyTo(newDs); } } finally { reader.dispose(); } writer.prepareWriteSequence(writeMeta); for (int i = 0; i < frames; i++) { FileInputStream inputStream = new FileInputStream(src); try { WritableRaster r = (WritableRaster) readRaster(inputStream, i); ColorModel cm = ColorModelFactory.createColorModel(ds); BufferedImage bi = new BufferedImage(cm, r, false, null); IIOImage iioimage = new IIOImage(bi, null, null); writer.writeToSequence(iioimage, null); } catch (NoSuchFieldException ex) { System.err.println(ex.toString()); } catch (IllegalAccessException ex) { System.err.println(ex.toString()); } finally { inputStream.close(); } } writer.endWriteSequence(); } finally { if (output != null) { output.close(); } } }
From source file:org.esa.s2tbx.dataio.s2.S2TileOpImage.java
protected void readTileData(File outputFile, int tileX, int tileY, int tileWidth, int tileHeight, int jp2TileX, int jp2TileY, int jp2TileWidth, int jp2TileHeight, short[] tileData, Rectangle destRect) throws IOException { // todo - we still have a synchronisation problem here: often zero areas are generated in a tile. // This does not happen, if we synchronise entire computeRect() on the instance, but it is less efficient. try (FileImageInputStream fis = new FileImageInputStream(outputFile)) { int jp2Width, jp2Height; final String[] tokens = fis.readLine().split(" "); long dataPos = fis.getStreamPosition(); if (tokens.length != 6) { throw new IOException("Unexpected PGX tile image format"); }/* w w w . java2s . c o m*/ // String pg = tokens[0]; // PG // String ml = tokens[1]; // ML // String plus = tokens[2]; // + try { // int jp2File.nbits = Integer.parseInt(tokens[3]); jp2Width = Integer.parseInt(tokens[4]); jp2Height = Integer.parseInt(tokens[5]); } catch (NumberFormatException e) { throw new IOException("Unexpected PGX tile image format"); } if (jp2Width > jp2TileWidth || jp2Height > jp2TileHeight) { throw new IllegalStateException( String.format("width (=%d) > tileWidth (=%d) || height (=%d) > tileHeight (=%d)", jp2Width, jp2TileWidth, jp2Height, jp2TileHeight)); } int jp2X = destRect.x - jp2TileX * jp2TileWidth; int jp2Y = destRect.y - jp2TileY * jp2TileHeight; if (jp2X < 0 || jp2Y < 0) { throw new IllegalStateException(String.format("jp2X (=%d) < 0 || jp2Y (=%d) < 0", jp2X, jp2Y)); } if (jp2X == 0 && jp2Width == tileWidth && jp2Y == 0 && jp2Height == tileHeight && tileWidth * tileHeight == tileData.length) { fis.seek(dataPos); fis.readFully(tileData, 0, tileData.length); } else { final Rectangle jp2FileRect = new Rectangle(0, 0, jp2Width, jp2Height); final Rectangle tileRect = new Rectangle(jp2X, jp2Y, tileWidth, tileHeight); final Rectangle intersection = jp2FileRect.intersection(tileRect); if (!intersection.isEmpty()) { SystemUtils.LOG .fine(String.format("%s: tile=(%d,%d): jp2FileRect=%s, tileRect=%s, intersection=%s\n", outputFile, tileX, tileY, jp2FileRect, tileRect, intersection)); long seekPos = dataPos + S2Config.SAMPLE_BYTE_COUNT * (intersection.y * jp2Width + intersection.x); int tilePos = 0; for (int y = 0; y < intersection.height; y++) { fis.seek(seekPos); fis.readFully(tileData, tilePos, intersection.width); seekPos += S2Config.SAMPLE_BYTE_COUNT * jp2Width; tilePos += tileWidth; for (int x = intersection.width; x < tileWidth; x++) { tileData[y * tileWidth + x] = S2Config.FILL_CODE_OUT_OF_X_BOUNDS; } } for (int y = intersection.height; y < tileHeight; y++) { for (int x = 0; x < tileWidth; x++) { tileData[y * tileWidth + x] = S2Config.FILL_CODE_OUT_OF_Y_BOUNDS; } } } else { Arrays.fill(tileData, S2Config.FILL_CODE_NO_INTERSECTION); } } } }
From source file:org.freecine.filmscan.ScanStrip.java
/** Load the scan strip image from disk/* ww w. java2s . co m*/ */ private void loadImage() { ImageReader reader; try { // PlanarImage img = JAI.create( "fileload", fname ); ImageInputStream istrm = new FileImageInputStream(file); reader = ImageIO.getImageReadersByFormatName("TIFF").next(); reader.setInput(istrm); ImageReadParam param = reader.getDefaultReadParam(); /* Set the color mode to linear sRGB as we don't have a better profile for the scanner/film available */ ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_LINEAR_RGB); ImageLayout layout = new ImageLayout(); ColorModel cm = new ComponentColorModel(cs, false, false, ColorModel.OPAQUE, DataBuffer.TYPE_USHORT); layout.setColorModel(cm); RenderingHints hints = new RenderingHints(JAI.KEY_IMAGE_LAYOUT, layout); stripImage = ImageReadDescriptor.create(istrm, 0, false, false, false, null, null, param, reader, hints); System.out.println("Color model " + stripImage.getColorModel()); // BufferedImage inImg = reader.read( 0, param ); } catch (FileNotFoundException ex) { System.out.println(ex.getMessage()); log.error("Strip file " + file + " not found", ex); } catch (IOException ex) { log.error("IO error reading strip " + file + ": ", ex); } }
From source file:org.geoserver.opensearch.rest.CollectionsController.java
private void configureSeparateBandsMosaic(String collection, CollectionLayer layerConfiguration, String relativePath, Resource mosaicDirectory) throws Exception { // get the namespace URI for the store final FeatureSource<FeatureType, Feature> collectionSource = getOpenSearchAccess().getCollectionSource(); final FeatureType schema = collectionSource.getSchema(); final String nsURI = schema.getName().getNamespaceURI(); // image mosaic won't automatically create the mosaic config for us in this case, // we have to setup both the mosaic property file and sample image for all bands for (int band : layerConfiguration.getBands()) { final String mosaicName = collection + OpenSearchAccess.BAND_LAYER_SEPARATOR + band; // get the sample granule File file = getSampleGranule(collection, nsURI, band, mosaicName); AbstractGridFormat format = (AbstractGridFormat) GridFormatFinder.findFormat(file, EXCLUDE_MOSAIC_HINTS);//from w ww . j a v a 2 s .c o m if (format == null) { throw new RestException( "Could not find a coverage reader able to process " + file.getAbsolutePath(), HttpStatus.PRECONDITION_FAILED); } ImageLayout imageLayout; double[] nativeResolution; AbstractGridCoverage2DReader reader = null; try { reader = format.getReader(file); if (reader == null) { throw new RestException( "Could not find a coverage reader able to process " + file.getAbsolutePath(), HttpStatus.PRECONDITION_FAILED); } imageLayout = reader.getImageLayout(); nativeResolution = reader.getResolutionLevels()[0]; } finally { if (reader != null) { reader.dispose(); } } ImageReaderSpi spi = null; try (FileImageInputStream fis = new FileImageInputStream(file)) { ImageReader imageReader = ImageIOExt.getImageioReader(fis); if (imageReader != null) { spi = imageReader.getOriginatingProvider(); } } // the mosaic configuration Properties mosaicConfig = new Properties(); mosaicConfig.put("Levels", nativeResolution[0] + "," + nativeResolution[1]); mosaicConfig.put("Heterogeneous", "true"); mosaicConfig.put("AbsolutePath", "true"); mosaicConfig.put("Name", "" + band); mosaicConfig.put("TypeName", mosaicName); mosaicConfig.put("TypeNames", "false"); // disable typename scanning mosaicConfig.put("Caching", "false"); mosaicConfig.put("LocationAttribute", "location"); mosaicConfig.put("TimeAttribute", TIME_START); mosaicConfig.put("CanBeEmpty", "true"); if (spi != null) { mosaicConfig.put("SuggestedSPI", spi.getClass().getName()); } // TODO: the index is now always in 4326, so the mosaic has to be heterogeneous // in general, unless we know the data is uniformly in something else, in that // case we could reproject the view reporting the footprints... // if (layerConfiguration.isHeterogeneousCRS()) { mosaicConfig.put("HeterogeneousCRS", "true"); mosaicConfig.put("MosaicCRS", "EPSG:4326" /* layerConfiguration.getMosaicCRS() */); mosaicConfig.put("CrsAttribute", "crs"); // } Resource propertyResource = mosaicDirectory.get(band + ".properties"); try (OutputStream os = propertyResource.out()) { mosaicConfig.store(os, "DataStore configuration for collection '" + collection + "' and band '" + band + "'"); } // create the sample image Resource sampleImageResource = mosaicDirectory.get(band + Utils.SAMPLE_IMAGE_NAME); Utils.storeSampleImage(sampleImageResource.file(), imageLayout.getSampleModel(null), imageLayout.getColorModel(null)); } // this is ridicolous, but for the moment, multi-crs mosaics won't work if there // is no indexer.properties around, even if no collection is actually done buildIndexer(collection, mosaicDirectory); // mosaic datastore connection createDataStoreProperties(collection, mosaicDirectory); // the mosaic datastore itself CatalogBuilder cb = new CatalogBuilder(catalog); CoverageStoreInfo mosaicStoreInfo = createMosaicStore(cb, collection, layerConfiguration, relativePath); // and finally the layer, with a coverage view associated to it List<CoverageBand> coverageBands = buildCoverageBands(layerConfiguration); final String coverageName = layerConfiguration.getLayer(); final CoverageView coverageView = new CoverageView(coverageName, coverageBands); CoverageInfo coverageInfo = coverageView.createCoverageInfo(coverageName, mosaicStoreInfo, cb); timeEnableResource(coverageInfo); final LayerInfo layerInfo = cb.buildLayer(coverageInfo); catalog.add(coverageInfo); catalog.add(layerInfo); // configure the style if needed createStyle(layerConfiguration, layerInfo); }
From source file:org.geoserver.wps.ppio.CoveragePPIOTest.java
private void testIsFormat(GridCoverage2D coverage, CoveragePPIO ppio, File encodedFile, String formatName) throws Exception { try (FileOutputStream fos = new FileOutputStream(encodedFile)) { ppio.encode(coverage, fos);// w ww . j a va 2 s.c o m } try (FileImageInputStream fis = new FileImageInputStream(encodedFile)) { ImageReader imageReader = null; try { imageReader = ImageIO.getImageReaders(fis).next(); imageReader.setInput(fis); assertTrue(formatName.equalsIgnoreCase(imageReader.getFormatName())); assertNotNull(imageReader.read(0)); } finally { if (imageReader != null) { try { imageReader.dispose(); } catch (Throwable t) { // Ignore it. } } } } }
From source file:org.olat.core.commons.services.image.spi.ImageHelperImpl.java
@Override public boolean cropImage(File image, File cropedImage, Crop cropSelection) { ImageInputStream imageSrc = null; try {/*from w w w . j a v a 2s .c om*/ imageSrc = new FileImageInputStream(image); String extension = FileUtils.getFileSuffix(cropedImage.getName()); SizeAndBufferedImage img = getImage(imageSrc, extension); BufferedImage croppedImg = cropTo(img.getImage(), img.getSize(), cropSelection); Size size = new Size(cropSelection.getWidth(), cropSelection.getHeight(), false); return writeTo(croppedImg, cropedImage, size, extension); } catch (IOException e) { return false; //fxdiff FXOLAT-109: prevent red screen if the image has wrong EXIF data } catch (CMMException e) { return false; } finally { closeQuietly(imageSrc); } }
From source file:org.olat.core.commons.services.image.spi.ImageHelperImpl.java
/** * @param image the image to scale//from www. ja v a2 s . c om * @param scaledImaged the new scaled image * @param maxSize the maximum size (height or width) of the new scaled image * @return */ @Override public Size scaleImage(File image, String imageExt, VFSLeaf scaledImage, int maxWidth, int maxHeight) { ImageInputStream imageIns = null; OutputStream bos = new BufferedOutputStream(scaledImage.getOutputStream(false)); try { imageIns = new FileImageInputStream(image); SizeAndBufferedImage scaledSize = calcScaledSize(imageIns, imageExt, maxWidth, maxHeight, false); if (scaledSize == null) { return null; } if (!scaledSize.getScaledSize().isChanged() && isSameFormat(image, scaledImage)) { InputStream cloneIns = new FileInputStream(image); IOUtils.copy(cloneIns, bos); IOUtils.closeQuietly(cloneIns); return scaledSize.getScaledSize(); } else { BufferedImage imageSrc = scaledSize.getImage(); if (imageSrc == null) { // happens with faulty Java implementation, e.g. on MacOSX Java 10, or // unsupported image format return null; } BufferedImage scaledBufferedImage = scaleTo(imageSrc, scaledSize.getScaledSize()); if (writeTo(scaledBufferedImage, bos, scaledSize.getScaledSize(), getImageFormat(scaledImage))) { return scaledSize.getScaledSize(); } return null; } } catch (IOException e) { return null; } finally { closeQuietly(imageIns); FileUtils.closeSafely(bos); } }
From source file:org.olat.core.commons.services.image.spi.ImageHelperImpl.java
/** * /*from ww w.ja va 2s . c om*/ * @param leaf * @return */ private ImageInputStream getInputStream(VFSLeaf leaf) throws IOException { if (leaf == null) { return null; } if (leaf instanceof LocalFileImpl) { LocalFileImpl file = (LocalFileImpl) leaf; if (file.getBasefile() != null) { return new FileImageInputStream(file.getBasefile()); } return null; } InputStream ins = leaf.getInputStream(); if (ins == null) { return null; } return new MemoryCacheImageInputStream(leaf.getInputStream()); }
From source file:org.olat.core.commons.services.image.spi.ImageHelperImpl.java
/** * @param image The image to scale/* ww w .j a va 2s . co m*/ * @param imageExt The extension if not given by the image file (optional) * @param scaledImaged the new scaled image * @param maxWidth the maximum width of the new scaled image * @param maxheight the maximum height of the new scaled image * @return */ @Override public Size scaleImage(File image, String imageExt, File scaledImage, int maxWidth, int maxHeight, boolean fill) { ImageInputStream imageSrc = null; try { imageSrc = new FileImageInputStream(image); SizeAndBufferedImage scaledSize = calcScaledSize(imageSrc, imageExt, maxWidth, maxHeight, fill); if (scaledSize == null || scaledSize.image == null) { return null; } if (!scaledSize.getScaledSize().isChanged() && isSameFormat(image, imageExt, scaledImage)) { if (FileUtils.copyFileToFile(image, scaledImage, false)) { return scaledSize.getSize(); } } BufferedImage bufferedImage = scaledSize.image; BufferedImage scaledBufferedImage = scaleTo(bufferedImage, scaledSize.getScaledSize()); if (writeTo(scaledBufferedImage, scaledImage, scaledSize.getScaledSize(), getImageFormat(scaledImage))) { return scaledSize.getScaledSize(); } return null; } catch (IOException e) { return null; //fxdiff FXOLAT-109: prevent red screen if the image has wrong EXIF data } catch (CMMException e) { return null; } finally { closeQuietly(imageSrc); } }