List of usage examples for javax.imageio ImageReader getNumImages
public abstract int getNumImages(boolean allowSearch) throws IOException;
From source file:Main.java
public Main(String filename) throws Exception { FileInputStream fin = new FileInputStream(filename); String suffix = filename.substring(filename.lastIndexOf('.') + 1); System.out.println("suf " + suffix); Iterator readers = ImageIO.getImageReadersBySuffix(suffix); ImageReader imageReader = (ImageReader) readers.next(); ImageInputStream iis = ImageIO.createImageInputStream(fin); imageReader.setInput(iis, false);//from w w w . j av a 2s.c o m int num = imageReader.getNumImages(true); images = new BufferedImage[num]; for (int i = 0; i < num; ++i) { images[i] = imageReader.read(i); } fin.close(); }
From source file:com.gargoylesoftware.htmlunit.javascript.host.canvas.rendering.AwtRenderingBackend.java
/** * {@inheritDoc}/* w ww . j av a 2s .c o m*/ */ public void drawImage(final ImageReader imageReader, final int dxI, final int dyI) throws IOException { if (imageReader.getNumImages(true) != 0) { final BufferedImage img = imageReader.read(0); graphics2D_.drawImage(img, dxI, dyI, null); } }
From source file:Main.java
public Main() throws Exception { String filename = "a.png"; FileInputStream inputStream = new FileInputStream(filename); String extensionName = filename.substring(filename.lastIndexOf('.') + 1); Iterator readers = ImageIO.getImageReadersBySuffix(extensionName); ImageReader imageReader = (ImageReader) readers.next(); ImageInputStream imageInputStream = ImageIO.createImageInputStream(inputStream); imageReader.setInput(imageInputStream, false); int num = imageReader.getNumImages(true); images = new BufferedImage[num]; for (int i = 0; i < num; ++i) { images[i] = imageReader.read(i); }/* w w w . ja v a 2 s .c o m*/ inputStream.close(); }
From source file:net.filterlogic.util.imaging.ToTIFF.java
/** * Convert multipage TIFF to single page TIFF. * @param srcFiles Array of source files to convert. * @param destPath Folder to store single page TIFFs in. * @param archivePath Path to move source TIFF files to after single page TIFFs created. * @param pattern Pattern of single page TIFF file names. Java NumberFormatter used with page number to create file name. * @param multipage Set to true if source TIFFs should be coverted to multi-page TIFF. * @param dpi DPI to set TIFFs to./*from w w w . ja v a 2s .co m*/ * @return Returns a list of files in destination path. * @throws net.filterlogic.util.imaging.OpenCaptureImagingException */ public static List toTIFF(String[] srcFiles, String destPath, String archivePath, String pattern, boolean multipage, int dpi) throws OpenCaptureImagingException { String pathSep = System.getProperty("file.separator"); boolean jaiSupport = true; int pageCount = 0; int fileNameCount = 0; byte[] imageData = null; // make sure destpath has trailing slash. if (destPath.lastIndexOf(pathSep) != destPath.length() - 1) destPath += pathSep; // create path if doesn't exist if (!Path.ValidatePath(destPath)) if (!Path.createPath(destPath)) throw new OpenCaptureImagingException( "Unable to create destination path for imported images [" + destPath + "]"); // make sure archivePath has trailing slash if (archivePath.lastIndexOf(pathSep) != archivePath.length() - 1) archivePath += pathSep; if (!Path.ValidatePath(archivePath)) if (!Path.createPath(archivePath)) throw new OpenCaptureImagingException( "Unable to create archive path for imported images [" + archivePath + "]"); // set a default pattern if one not passed. if (pattern.trim().length() < 1) pattern = "#"; NumberFormat formatter = new DecimalFormat(pattern); ArrayList<String> list = new ArrayList<String>(); for (int i = 0; i < srcFiles.length; i++) { try { File f = new File(srcFiles[i]); imageData = null; ImageIO.setUseCache(false); ImageInputStream imageInputStream = ImageIO.createImageInputStream(f); java.util.Iterator readers = ImageIO.getImageReaders(imageInputStream); ImageReader reader1 = null; if (readers.hasNext()) { reader1 = (ImageReader) readers.next(); jaiSupport = true; } else jaiSupport = false; if (jaiSupport) { //ImageInputStream iis = ImageIO.createImageInputStream(new FileInputStream(f)); reader1.setInput(imageInputStream); pageCount = reader1.getNumImages(true); } else { String newFileName = bigEndian2LittleEndian(f.getAbsolutePath()); if (imageInputStream != null) { imageInputStream.flush(); imageInputStream.close(); reader1.setInput(imageInputStream); pageCount = reader1.getNumImages(true); } imageInputStream = ImageIO.createImageInputStream(new File(newFileName)); readers = ImageIO.getImageReaders(imageInputStream); } // Iterator writers = ImageIO.getImageWritersByFormatName("tiff"); // ImageWriter writer = (ImageWriter)writers.next(); //ImageWriteParam param = writer.getDefaultWriteParam(); //param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); //String[] legalTypes = param.getCompressionTypes(); //param.setCompressionType("PackBits"); //ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); ImageOutputStream ios = null; BufferedImage img = null; // break out each page to single file for (int t = 0; t < pageCount; t++) { // format filenumber String tifName = destPath + formatter.format(fileNameCount) + ".tif"; while (new File(tifName).exists()) { tifName = destPath + formatter.format(++fileNameCount) + ".tif"; } FileOutputStream file = new FileOutputStream(new File(tifName)); if (jaiSupport) { img = reader1.read(t); IIOImage iioimg = reader1.readAll(t, null); //ios = ImageIO.createImageOutputStream(file); //IIOMetadata iiom = getMetadata(writer, img, null, 200); } else { img = loadTIFF(imageData, t); } TIFFEncodeParam tep = setEncoder(TIFFEncodeParam.COMPRESSION_PACKBITS, 200); ImageEncoder encoder = ImageCodec.createImageEncoder("TIFF", file, tep); encoder.encode(img); //boolean ok = ImageIO.write(img, "tiff", ios); //writer.setOutput(ios); //writer.write(iiom, iioimg, null); img.flush(); //ios.flush(); //ios.close(); // ios = null; //iioimg = null; //iiom = null; img = null; //writer.dispose(); //byteOut.flush(); file.close(); file = null; //System.out.println("Add file!"); list.add(tifName); } if (jaiSupport) { reader1.dispose(); } readers = null; // writer.dispose(); // writers = null; imageInputStream.flush(); imageInputStream.close(); imageInputStream = null; f = null; // move file with overwrite if (!net.filterlogic.io.FileAccess.Move(srcFiles[i], archivePath, true)) throw new Exception("Unable to move input file to archive path [" + srcFiles[i] + "] to [" + archivePath + "]"); } catch (Exception e) { throw new OpenCaptureImagingException(e.toString()); } } return list; }
From source file:ImageIOTest.java
/** * Open a file and load the images.//from www. j av a 2s .c o m */ public void openFile() { JFileChooser chooser = new JFileChooser(); chooser.setCurrentDirectory(new File(".")); String[] extensions = ImageIO.getReaderFileSuffixes(); chooser.setFileFilter(new FileNameExtensionFilter("Image files", extensions)); int r = chooser.showOpenDialog(this); if (r != JFileChooser.APPROVE_OPTION) return; File f = chooser.getSelectedFile(); Box box = Box.createVerticalBox(); try { String name = f.getName(); String suffix = name.substring(name.lastIndexOf('.') + 1); Iterator<ImageReader> iter = ImageIO.getImageReadersBySuffix(suffix); ImageReader reader = iter.next(); ImageInputStream imageIn = ImageIO.createImageInputStream(f); reader.setInput(imageIn); int count = reader.getNumImages(true); images = new BufferedImage[count]; for (int i = 0; i < count; i++) { images[i] = reader.read(i); box.add(new JLabel(new ImageIcon(images[i]))); } } catch (IOException e) { JOptionPane.showMessageDialog(this, e); } setContentPane(new JScrollPane(box)); validate(); }
From source file:com.gargoylesoftware.htmlunit.javascript.host.canvas.CanvasRenderingContext2D.java
/** * Draws images onto the canvas.//from ww w. j av a2 s . c o m * * @param image an element to draw into the context * @param sx the X coordinate of the top left corner of the sub-rectangle of the source image * to draw into the destination context * @param sy the Y coordinate of the top left corner of the sub-rectangle of the source image * to draw into the destination context * @param sWidth the width of the sub-rectangle of the source image to draw into the destination context * @param sHeight the height of the sub-rectangle of the source image to draw into the destination context * @param dx the X coordinate in the destination canvas at which to place the top-left corner of the source image * @param dy the Y coordinate in the destination canvas at which to place the top-left corner of the source image * @param dWidth the width to draw the image in the destination canvas. This allows scaling of the drawn image * @param dHeight the height to draw the image in the destination canvas. This allows scaling of the drawn image */ @JsxFunction @SuppressWarnings("unused") public void drawImage(final Object image, final int sx, final int sy, final Object sWidth, final Object sHeight, final Object dx, final Object dy, final Object dWidth, final Object dHeight) { Integer dxI; Integer dyI; Integer dWidthI = null; Integer dHeightI = null; Integer sWidthI = null; Integer sHeightI = null; if (dx != Undefined.instance) { dxI = ((Number) dx).intValue(); dyI = ((Number) dy).intValue(); dWidthI = ((Number) dWidth).intValue(); dHeightI = ((Number) dHeight).intValue(); } else { dxI = sx; dyI = sy; } if (sWidth != Undefined.instance) { sWidthI = ((Number) sWidth).intValue(); sHeightI = ((Number) sHeight).intValue(); } try { if (image instanceof HTMLImageElement) { final ImageReader imageReader = ((HtmlImage) ((HTMLImageElement) image).getDomNodeOrDie()) .getImageReader(); if (imageReader.getNumImages(true) != 0) { final BufferedImage img = imageReader.read(0); graphics2D_.drawImage(img, dxI, dyI, null); } } } catch (final IOException ioe) { throw Context.throwAsScriptRuntimeEx(ioe); } }
From source file:net.filterlogic.util.imaging.ToTIFF.java
/** * /*from www .j av a 2 s . co m*/ * @param fileName */ public void test6(String fileName) { try { File f = new File(fileName); ImageInputStream imageInputStream = ImageIO.createImageInputStream(f); java.util.Iterator readers = ImageIO.getImageReaders(imageInputStream); ImageReader reader1 = (ImageReader) readers.next(); ImageInputStream iis = ImageIO.createImageInputStream(new FileInputStream(f)); reader1.setInput(iis); int number = reader1.getNumImages(true); Iterator writers = ImageIO.getImageWritersByFormatName("tiff"); ImageWriter writer = (ImageWriter) writers.next(); ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); ImageOutputStream ios = null; BufferedImage img = null; for (int i = 0; i < number; i++) { img = reader1.read(i); ios = ImageIO.createImageOutputStream(byteOut); writer.setOutput(ios); writer.write(img); ios.flush(); img.flush(); byteOut.flush(); } } catch (Exception e) { System.out.println(e.toString()); } }
From source file:com.occamlab.te.parsers.ImageParser.java
private static Document parse(InputStream source, Element instruction, PrintWriter logger) throws Exception { ImageReader reader; try {/*from w w w .ja v a 2 s . c om*/ ImageInputStream iis = ImageIO.createImageInputStream(source); reader = ImageIO.getImageReaders(iis).next(); reader.setInput(iis); } catch (Exception e) { logger.println("No image handlers available for the data stream. " + e.getMessage()); throw e; } DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.newDocument(); TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = tf.newTransformer(); t.transform(new DOMSource(instruction), new DOMResult(doc)); Element new_instruction = doc.getDocumentElement(); int framesRead = 0; boolean containsFrames = false; Element framesElement = null; Element metadataElement = null; NodeList nodes = new_instruction.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { // System.out.println(node.getLocalName()); if (node.getLocalName().equals("type")) { node.setTextContent(reader.getFormatName().toLowerCase()); } else if (node.getLocalName().equals("frames")) { framesElement = (Element) node; containsFrames = true; } else if (node.getLocalName().equals("metadata")) { metadataElement = (Element) node; } else if (node.getLocalName().equals("frame")) { int frame; String frameStr = ((Element) node).getAttribute("num"); if (frameStr.length() == 0) { frame = framesRead; framesRead++; ((Element) node).setAttribute("num", Integer.toString(frame)); } else { frame = Integer.parseInt(frameStr); framesRead = frame + 1; } processFrame(reader, frame, node.getChildNodes(), logger); containsFrames = true; } } } if (containsFrames) { if (metadataElement != null) { IIOMetadata metadata = reader.getStreamMetadata(); if (metadata != null) { String format = metadataElement.getAttribute("format"); if (format.length() == 0) { format = metadata.getNativeMetadataFormatName(); } Node tree = metadata.getAsTree(format); t.transform(new DOMSource(tree), new DOMResult(metadataElement)); } } if (framesElement != null) { boolean allowSearch = !reader.isSeekForwardOnly(); int frames = reader.getNumImages(allowSearch); if (frames == -1) { try { while (true) { reader.read(framesRead); framesRead++; } } catch (Exception e) { jlogger.log(Level.SEVERE, "", e); frames = framesRead + 1; } } framesElement.setTextContent(Integer.toString(frames)); } } else { processFrame(reader, 0, nodes, logger); framesRead = 1; } // t.transform(new DOMSource(doc), new StreamResult(System.out)); return doc; }
From source file:org.geotools.gce.imagemosaic.GranuleDescriptor.java
private void init(final BoundingBox granuleBBOX, final URL granuleUrl, final ImageReaderSpi suggestedSPI, final MultiLevelROI roiProvider, final boolean heterogeneousGranules, final boolean handleArtifactsFiltering, final Hints hints) { this.granuleBBOX = ReferencedEnvelope.reference(granuleBBOX); this.granuleUrl = granuleUrl; this.roiProvider = roiProvider; this.handleArtifactsFiltering = handleArtifactsFiltering; filterMe = handleArtifactsFiltering && roiProvider != null; // create the base grid to world transformation ImageInputStream inStream = null; ImageReader reader = null; try {//from www . ja v a2s .co m // //get info about the raster we have to read // // get a stream if (cachedStreamSPI == null) { cachedStreamSPI = ImageIOExt.getImageInputStreamSPI(granuleUrl, true); if (cachedStreamSPI == null) { final File file = DataUtilities.urlToFile(granuleUrl); if (file != null) { if (LOGGER.isLoggable(Level.WARNING)) { LOGGER.log(Level.WARNING, Utils.getFileInfo(file)); } } throw new IllegalArgumentException( "Unable to get an input stream for the provided granule " + granuleUrl.toString()); } } assert cachedStreamSPI != null : "no cachedStreamSPI available!"; inStream = cachedStreamSPI.createInputStreamInstance(granuleUrl, ImageIO.getUseCache(), ImageIO.getCacheDirectory()); if (inStream == null) { final File file = DataUtilities.urlToFile(granuleUrl); if (file != null) { if (LOGGER.isLoggable(Level.WARNING)) { LOGGER.log(Level.WARNING, Utils.getFileInfo(file)); } } throw new IllegalArgumentException( "Unable to get an input stream for the provided file " + granuleUrl.toString()); } // get a reader and try to cache the suggested SPI first if (cachedReaderSPI == null) { inStream.mark(); if (suggestedSPI != null && suggestedSPI.canDecodeInput(inStream)) { cachedReaderSPI = suggestedSPI; inStream.reset(); } else { inStream.mark(); reader = ImageIOExt.getImageioReader(inStream); if (reader != null) cachedReaderSPI = reader.getOriginatingProvider(); inStream.reset(); } } if (reader == null) { if (cachedReaderSPI == null) { throw new IllegalArgumentException( "Unable to get a ReaderSPI for the provided input: " + granuleUrl.toString()); } reader = cachedReaderSPI.createReaderInstance(); } if (reader == null) throw new IllegalArgumentException( "Unable to get an ImageReader for the provided file " + granuleUrl.toString()); boolean ignoreMetadata = customizeReaderInitialization(reader, hints); reader.setInput(inStream, false, ignoreMetadata); //get selected level and base level dimensions final Rectangle originalDimension = Utils.getDimension(0, reader); // build the g2W for this tile, in principle we should get it // somehow from the tile itself or from the index, but at the moment // we do not have such info, hence we assume that it is a simple // scale and translate this.geMapper = new GridToEnvelopeMapper(new GridEnvelope2D(originalDimension), granuleBBOX); geMapper.setPixelAnchor(PixelInCell.CELL_CENTER);//this is the default behavior but it is nice to write it down anyway this.baseGridToWorld = geMapper.createAffineTransform(); // add the base level this.granuleLevels.put(Integer.valueOf(0), new GranuleOverviewLevelDescriptor(1, 1, originalDimension.width, originalDimension.height)); ////////////////////// Setting overviewController /////////////////////// if (heterogeneousGranules) { // // // // Right now we are setting up overviewsController by assuming that // overviews are internal images as happens in TIFF images // We can improve this by leveraging on coverageReaders // // // // Getting the first level descriptor final GranuleOverviewLevelDescriptor baseOverviewLevelDescriptor = granuleLevels.get(0); // Variables initialization final int numberOfOvervies = reader.getNumImages(true) - 1; final AffineTransform2D baseG2W = baseOverviewLevelDescriptor.getGridToWorldTransform(); final int width = baseOverviewLevelDescriptor.getWidth(); final int height = baseOverviewLevelDescriptor.getHeight(); final double resX = AffineTransform2D.getScaleX0(baseG2W); final double resY = AffineTransform2D.getScaleY0(baseG2W); final double[] highestRes = new double[] { resX, resY }; final double[][] overviewsResolution = new double[numberOfOvervies][2]; // Populating overviews and initializing overviewsController for (int i = 0; i < numberOfOvervies; i++) { overviewsResolution[i][0] = (highestRes[0] * width) / reader.getWidth(i + 1); overviewsResolution[i][1] = (highestRes[1] * height) / reader.getHeight(i + 1); } overviewsController = new OverviewsController(highestRes, numberOfOvervies, overviewsResolution); } ////////////////////////////////////////////////////////////////////////// if (hints != null && hints.containsKey(Utils.CHECK_AUXILIARY_METADATA)) { boolean checkAuxiliaryMetadata = (Boolean) hints.get(Utils.CHECK_AUXILIARY_METADATA); if (checkAuxiliaryMetadata) { checkPamDataset(); } } } catch (IllegalStateException e) { throw new IllegalArgumentException(e); } catch (IOException e) { throw new IllegalArgumentException(e); } finally { // close/dispose stream and readers try { if (inStream != null) { inStream.close(); } } catch (Throwable e) { throw new IllegalArgumentException(e); } finally { if (reader != null) { reader.dispose(); } } } }
From source file:org.geotools.utils.imagemosaic.MosaicIndexBuilder.java
/** * Main thread for the mosaic index builder. *//*from ww w. j av a2s .c o m*/ public void run() { // ///////////////////////////////////////////////////////////////////// // // CREATING INDEX FILE // // ///////////////////////////////////////////////////////////////////// // ///////////////////////////////////////////////////////////////////// // // Create a file handler that write log record to a file called // my.log // // ///////////////////////////////////////////////////////////////////// FileHandler handler = null; try { boolean append = true; handler = new FileHandler(new StringBuffer(locationPath).append("/error.txt").toString(), append); handler.setLevel(Level.SEVERE); // Add to the desired logger LOGGER.addHandler(handler); // ///////////////////////////////////////////////////////////////////// // // Create a set of file names that have to be skipped since these are // our metadata files // // ///////////////////////////////////////////////////////////////////// final Set<String> skipFiles = new HashSet<String>( Arrays.asList(new String[] { indexName + ".shp", indexName + ".dbf", indexName + ".shx", indexName + ".prj", "error.txt", "error.txt.lck", indexName + ".properties" })); // ///////////////////////////////////////////////////////////////////// // // Creating temp vars // // ///////////////////////////////////////////////////////////////////// ShapefileDataStore index = null; Transaction t = new DefaultTransaction(); // declaring a preciosion model to adhere the java double type // precision PrecisionModel precMod = new PrecisionModel(PrecisionModel.FLOATING); GeometryFactory geomFactory = new GeometryFactory(precMod); try { index = new ShapefileDataStore( new File(locationPath + File.separator + indexName + ".shp").toURI().toURL()); } catch (MalformedURLException ex) { if (LOGGER.isLoggable(Level.SEVERE)) LOGGER.log(Level.SEVERE, ex.getLocalizedMessage(), ex); fireException(ex); return; } final List<File> files = new ArrayList<File>(); recurse(files, locationPath); // ///////////////////////////////////////////////////////////////////// // // Cycling over the files that have filtered out // // ///////////////////////////////////////////////////////////////////// numFiles = files.size(); String validFileName = null; final Iterator<File> filesIt = files.iterator(); FeatureWriter<SimpleFeatureType, SimpleFeature> fw = null; boolean doneSomething = false; for (int i = 0; i < numFiles; i++) { StringBuffer message; // // // // Check that this file is actually good to go // // // final File fileBeingProcessed = ((File) filesIt.next()); if (!fileBeingProcessed.exists() || !fileBeingProcessed.canRead() || !fileBeingProcessed.isFile()) { // send a message message = new StringBuffer("Skipped file ").append(files.get(i)) .append(" snce it seems invalid."); if (LOGGER.isLoggable(Level.INFO)) LOGGER.info(message.toString()); fireEvent(message.toString(), ((i * 99.0) / numFiles)); continue; } // // // // Anyone has asked us to stop? // // // if (getStopThread()) { message = new StringBuffer("Stopping requested at file ").append(i).append(" of ") .append(numFiles).append(" files"); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine(message.toString()); } fireEvent(message.toString(), ((i * 100.0) / numFiles)); return; } // replacing chars on input path try { validFileName = fileBeingProcessed.getCanonicalPath(); } catch (IOException e1) { fireException(e1); return; } validFileName = validFileName.replace('\\', '/'); validFileName = validFileName.substring(locationPath.length() + 1, fileBeingProcessed.getAbsolutePath().length()); if (skipFiles.contains(validFileName)) continue; message = new StringBuffer("Now indexing file ").append(validFileName); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine(message.toString()); } fireEvent(message.toString(), ((i * 100.0) / numFiles)); try { // //////////////////////////////////////////////////////// // // // STEP 1 // Getting an ImageIO reader for this coverage. // // // //////////////////////////////////////////////////////// ImageInputStream inStream = ImageIO.createImageInputStream(fileBeingProcessed); if (inStream == null) { if (LOGGER.isLoggable(Level.SEVERE)) LOGGER.severe(fileBeingProcessed + " has been skipped since we could not get a stream for it"); continue; } inStream.mark(); final Iterator<ImageReader> it = ImageIO.getImageReaders(inStream); ImageReader r = null; if (it.hasNext()) { r = (ImageReader) it.next(); r.setInput(inStream); } else { // release resources try { inStream.close(); } catch (Exception e) { // ignore exception } // try { // r.dispose(); // } catch (Exception e) { // // ignore exception // } // send a message message = new StringBuffer("Skipped file ").append(files.get(i)) .append(":No ImageIO readeres avalaible."); if (LOGGER.isLoggable(Level.INFO)) LOGGER.info(message.toString()); fireEvent(message.toString(), ((i * 99.0) / numFiles)); continue; } // //////////////////////////////////////////////////////// // // STEP 2 // Getting a coverage reader for this coverage. // // //////////////////////////////////////////////////////// if (LOGGER.isLoggable(Level.FINE)) LOGGER.fine(new StringBuffer("Getting a reader").toString()); final AbstractGridFormat format = (AbstractGridFormat) GridFormatFinder .findFormat(files.get(i)); if (format == null || !format.accepts(files.get(i))) { // release resources try { inStream.close(); } catch (Exception e) { // ignore exception } try { r.dispose(); } catch (Exception e) { // ignore exception } message = new StringBuffer("Skipped file ").append(files.get(i)) .append(": File format is not supported."); if (LOGGER.isLoggable(Level.INFO)) LOGGER.info(message.toString()); fireEvent(message.toString(), ((i * 99.0) / numFiles)); continue; } final AbstractGridCoverage2DReader reader = (AbstractGridCoverage2DReader) format .getReader(files.get(i)); envelope = (GeneralEnvelope) reader.getOriginalEnvelope(); actualCRS = reader.getCrs(); // ///////////////////////////////////////////////////////////////////// // // STEP 3 // Get the type specifier for this image and the check that the // image has the correct sample model and color model. // If this is the first cycle of the loop we initialize // eveything. // // ///////////////////////////////////////////////////////////////////// final ImageTypeSpecifier its = ((ImageTypeSpecifier) r.getImageTypes(0).next()); boolean skipFeature = false; if (globEnvelope == null) { // ///////////////////////////////////////////////////////////////////// // // at the first step we initialize everything that we will // reuse afterwards starting with color models, sample // models, crs, etc.... // // ///////////////////////////////////////////////////////////////////// defaultCM = its.getColorModel(); if (defaultCM instanceof IndexColorModel) { IndexColorModel icm = (IndexColorModel) defaultCM; int numBands = defaultCM.getNumColorComponents(); defaultPalette = new byte[3][icm.getMapSize()]; icm.getReds(defaultPalette[0]); icm.getGreens(defaultPalette[0]); icm.getBlues(defaultPalette[0]); if (numBands == 4) icm.getAlphas(defaultPalette[0]); } defaultSM = its.getSampleModel(); defaultCRS = actualCRS; globEnvelope = new GeneralEnvelope(envelope); // ///////////////////////////////////////////////////////////////////// // // getting information about resolution // // ///////////////////////////////////////////////////////////////////// // // // // get the dimension of the hr image and build the model // as well as // computing the resolution // // // resetting reader and recreating stream, turnaround for a // strange imageio bug r.reset(); try { inStream.reset(); } catch (IOException e) { inStream = ImageIO.createImageInputStream(fileBeingProcessed); } //let's check if we got something now if (inStream == null) { //skip file if (LOGGER.isLoggable(Level.WARNING)) LOGGER.warning("Skipping file " + fileBeingProcessed.toString()); continue; } r.setInput(inStream); numberOfLevels = r.getNumImages(true); resolutionLevels = new double[2][numberOfLevels]; double[] res = getResolution(envelope, new Rectangle(r.getWidth(0), r.getHeight(0)), defaultCRS); resolutionLevels[0][0] = res[0]; resolutionLevels[1][0] = res[1]; // resolutions levels if (numberOfLevels > 1) { for (int k = 0; k < numberOfLevels; k++) { res = getResolution(envelope, new Rectangle(r.getWidth(k), r.getHeight(k)), defaultCRS); resolutionLevels[0][k] = res[0]; resolutionLevels[1][k] = res[1]; } } // ///////////////////////////////////////////////////////////////////// // // creating the schema // // ///////////////////////////////////////////////////////////////////// final SimpleFeatureTypeBuilder featureBuilder = new SimpleFeatureTypeBuilder(); featureBuilder.setName("Flag"); featureBuilder.setNamespaceURI("http://www.geo-solutions.it/"); featureBuilder.add("location", String.class); featureBuilder.add("the_geom", Polygon.class, this.actualCRS); featureBuilder.setDefaultGeometry("the_geom"); final SimpleFeatureType simpleFeatureType = featureBuilder.buildFeatureType(); // create the schema for the new shape file index.createSchema(simpleFeatureType); // get a feature writer fw = index.getFeatureWriter(t); } else { // //////////////////////////////////////////////////////// // // comparing ColorModel // comparing SampeModel // comparing CRSs // //////////////////////////////////////////////////////// globEnvelope.add(envelope); actualCM = its.getColorModel(); actualSM = its.getSampleModel(); skipFeature = (i > 0 ? !(CRS.equalsIgnoreMetadata(defaultCRS, actualCRS)) : false); if (skipFeature) LOGGER.warning(new StringBuffer("Skipping image ").append(files.get(i)) .append(" because CRSs do not match.").toString()); skipFeature = checkColorModels(defaultCM, defaultPalette, actualCM); if (skipFeature) LOGGER.warning(new StringBuffer("Skipping image ").append(files.get(i)) .append(" because color models do not match.").toString()); // defaultCM.getNumComponents()==actualCM.getNumComponents()&& // defaultCM.getClass().equals(actualCM.getClass()) // && defaultSM.getNumBands() == actualSM // .getNumBands() // && defaultSM.getDataType() == actualSM // .getDataType() && // // if (skipFeature) // LOGGER // .warning(new StringBuffer("Skipping image ") // .append(files.get(i)) // .append( // " because cm or sm does not match.") // .toString()); // res = getResolution(envelope, new // Rectangle(r.getWidth(0), // r.getHeight(0)), defaultCRS); // if (Math.abs((resX - res[0]) / resX) > EPS // || Math.abs(resY - res[1]) > EPS) { // LOGGER.warning(new StringBuffer("Skipping image // ").append( // files.get(i)).append( // " because resolutions does not match.") // .toString()); // skipFeature = true; // } } // //////////////////////////////////////////////////////// // // STEP 4 // // create and store features // // //////////////////////////////////////////////////////// if (!skipFeature) { final SimpleFeature feature = fw.next(); feature.setAttribute(1, geomFactory.toGeometry(new ReferencedEnvelope((Envelope) envelope))); feature.setAttribute( 0, absolute ? new StringBuilder(this.locationPath).append(File.separatorChar) .append(validFileName).toString() : validFileName); fw.write(); message = new StringBuffer("Done with file ").append(files.get(i)); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine(message.toString()); } message.append('\n'); fireEvent(message.toString(), (((i + 1) * 99.0) / numFiles)); doneSomething = true; } else skipFeature = false; // //////////////////////////////////////////////////////// // // STEP 5 // // release resources // // //////////////////////////////////////////////////////// try { inStream.close(); } catch (Exception e) { // ignore exception } try { r.dispose(); } catch (Exception e) { // ignore exception } // release resources reader.dispose(); } catch (IOException e) { fireException(e); break; } catch (ArrayIndexOutOfBoundsException e) { fireException(e); break; } } try { if (fw != null) fw.close(); t.commit(); t.close(); index.dispose(); } catch (IOException e) { LOGGER.log(Level.SEVERE, e.getLocalizedMessage(), e); } createPropertiesFiles(globEnvelope, doneSomething); } catch (SecurityException el) { fireException(el); return; } catch (IOException el) { fireException(el); return; } finally { try { if (handler != null) handler.close(); } catch (Throwable e) { // ignore } } }