List of usage examples for javax.imageio ImageIO getImageReaders
public static Iterator<ImageReader> getImageReaders(Object input)
From source file:org.geotools.utils.imagemosaic.MosaicIndexBuilder.java
/** * Main thread for the mosaic index builder. *//*from w w w . ja v a 2 s. com*/ 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 } } }
From source file:iqq.util.ImageUtil.java
/** * ??/*from w ww . ja v a2 s.c o m*/ * * @param imageFile * @return ? */ public static String getFormatName(File imageFile) { if (imageFile == null || imageFile.length() == 0) { return null; } try { String formatName = null; ImageInputStream imageInputStream = ImageIO.createImageInputStream(imageFile); Iterator<ImageReader> iterator = ImageIO.getImageReaders(imageInputStream); if (!iterator.hasNext()) { return null; } ImageReader imageReader = iterator.next(); if (imageReader instanceof JPEGImageReader) { formatName = JPEG_FORMAT_NAME; } else if (imageReader instanceof GIFImageReader) { formatName = GIF_FORMAT_NAME; } else if (imageReader instanceof BMPImageReader) { formatName = BMP_FORMAT_NAME; } else if (imageReader instanceof PNGImageReader) { formatName = PNG_FORMAT_NAME; } imageInputStream.close(); return formatName; } catch (IOException e) { e.printStackTrace(); return null; } }
From source file:lucee.runtime.img.Image.java
public IIOMetadata getMetaData(Struct parent) { InputStream is = null;/*from w ww . j a v a 2 s.co m*/ javax.imageio.stream.ImageInputStreamImpl iis = null; try { if (source instanceof File) { iis = new FileImageInputStream((File) source); } else if (source == null) iis = new MemoryCacheImageInputStream(new ByteArrayInputStream(getImageBytes(format, true))); else iis = new MemoryCacheImageInputStream(is = source.getInputStream()); Iterator<ImageReader> readers = ImageIO.getImageReaders(iis); if (readers.hasNext()) { // pick the first available ImageReader ImageReader reader = readers.next(); IIOMetadata meta = null; synchronized (sync) { // attach source to the reader reader.setInput(iis, true); // read metadata of first image meta = reader.getImageMetadata(0); meta.setFromTree(FORMAT, meta.getAsTree(FORMAT)); reader.reset(); } // generating dump if (parent != null) { String[] formatNames = meta.getMetadataFormatNames(); for (int i = 0; i < formatNames.length; i++) { Node root = meta.getAsTree(formatNames[i]); //print.out(XMLCaster.toString(root)); addMetaddata(parent, "metadata", root); } } return meta; } } catch (Throwable t) { } finally { ImageUtil.closeEL(iis); IOUtil.closeEL(is); } return null; }
From source file:com.occamlab.te.parsers.ImageParser.java
/** * Determines the width of the first image in an image file in pixels. * //from w w w.ja v a 2 s . c o m * @param imageLoc * the string location of the image (uri syntax expected) * @return int the image width in pixels, or -1 if unable. * @author Paul Daisey added 2011-05-13 to support WMTS ETS */ public static int getImageWidth(String imageLoc) { // Get the image as an InputStream InputStream is = null; try { URI imageUri = new URI(imageLoc); URL imageUrl = imageUri.toURL(); is = imageUrl.openStream(); } catch (Exception e) { jlogger.log(Level.SEVERE, "getImageWidth", e); return -1; } // Determine the image width try { // Create an image input stream on the image ImageInputStream iis = ImageIO.createImageInputStream(is); // Find all image readers that recognize the image format Iterator iter = ImageIO.getImageReaders(iis); // No readers found if (!iter.hasNext()) { return -1; } // Use the first reader ImageReader reader = (ImageReader) iter.next(); reader.setInput(iis, true); int width = reader.getWidth(0); iis.close(); return width; } catch (IOException e) { jlogger.log(Level.SEVERE, "getImageWidth", e); // The image could not be read } return -1; }
From source file:com.gargoylesoftware.htmlunit.html.HtmlImage.java
private void readImageIfNeeded() throws IOException { downloadImageIfNeeded();//from w ww .j a v a 2 s . com if (imageData_ == null) { if (null == imageWebResponse_) { throw new IOException("No image response available (src=" + getSrcAttribute() + ")"); } final ImageInputStream iis = ImageIO.createImageInputStream(imageWebResponse_.getContentAsStream()); final Iterator<ImageReader> iter = ImageIO.getImageReaders(iis); if (!iter.hasNext()) { iis.close(); throw new IOException("No image detected in response"); } final ImageReader imageReader = iter.next(); imageReader.setInput(iis); imageData_ = new ImageData(imageReader); // dispose all others while (iter.hasNext()) { iter.next().dispose(); } } }
From source file:com.occamlab.te.parsers.ImageParser.java
/** * Determines the height of the first image in an image file in pixels. * /*from w w w . jav a 2s .c o m*/ * @param imageLoc * the string location of the image (uri syntax expected) * @return int the image width in pixels, or -1 if unable. * @author Paul Daisey added 2011-05-13 to support WMTS ETS */ public static int getImageHeight(String imageLoc) { // Get the image as an InputStream InputStream is = null; try { URI imageUri = new URI(imageLoc); URL imageUrl = imageUri.toURL(); is = imageUrl.openStream(); } catch (Exception e) { jlogger.log(Level.SEVERE, "getImageWidth", e); return -1; } // Determine the image width try { // Create an image input stream on the image ImageInputStream iis = ImageIO.createImageInputStream(is); // Find all image readers that recognize the image format Iterator iter = ImageIO.getImageReaders(iis); // No readers found if (!iter.hasNext()) { return -1; } // Use the first reader ImageReader reader = (ImageReader) iter.next(); reader.setInput(iis, true); int height = reader.getHeight(0); iis.close(); return height; } catch (IOException e) { jlogger.log(Level.SEVERE, "getImageWidth", e); // The image could not be read } return -1; }
From source file:immf.Util.java
@SuppressWarnings("unchecked") public static InputStream png2gif(InputStream is) throws IOException { InputStream gis = null;/*from w ww . ja v a 2s. c om*/ BufferedInputStream pis = new BufferedInputStream(is); try { // iPhone iOS??iOS 4.3??????? pis.mark(0); ImageInputStream iis = ImageIO.createImageInputStream(pis); Iterator i = ImageIO.getImageReaders(iis); if (i.hasNext() && ((ImageReader) i.next()).getFormatName().equals("gif")) { // ???gif????????????? pis.reset(); gis = pis; } } catch (Exception e) { } finally { pis.reset(); } if (gis != null) { return gis; } // PNG -> GIF? try { BufferedImage png = ImageIO.read(pis); ByteArrayOutputStream converted = new ByteArrayOutputStream(); if (ImageIO.write(png, "gif", converted)) { gis = new ByteArrayInputStream(converted.toByteArray()); } } catch (Exception e) { } if (gis != null) { return gis; } else { pis.reset(); return pis; } }
From source file:org.medici.bia.controller.manuscriptviewer.IIPImageServerController.java
/** * /* w w w. j ava2s .c o m*/ * @param imageName * @param thumbnailWidth * @param thumbnailFormat * @param response */ private void generateThumbnailImage(String imageName, Double thumbnailWidth, Integer imageQuality, String thumbnailFormat, HttpServletResponse httpServletResponse) { File imageFile = new File( ApplicationPropertyManager.getApplicationProperty("iipimage.image.path") + imageName); ImageInputStream imageInputStream = null; ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); InputStream inputStream = null; try { if (imageFile.canRead()) { // Reading complete tiff information imageInputStream = ImageIO.createImageInputStream(imageFile); } else { logger.error("File " + imageFile.toString() + " is not present on filesystem. "); imageFile = new File(ApplicationPropertyManager.getApplicationProperty("iipimage.image.path") + ApplicationPropertyManager.getApplicationProperty("iipimage.image.notavailable")); if (imageFile.canRead()) { // Reading complete tiff information imageInputStream = ImageIO.createImageInputStream(imageFile); } else { logger.error("File " + imageFile.toString() + " is not present on filesystem. "); } } if (imageInputStream != null) { Iterator<ImageReader> readers = ImageIO.getImageReaders(imageInputStream); if (readers.hasNext()) { ImageReader reader = readers.next(); reader.setInput(imageInputStream, false, true); BufferedImage page = null; if (reader.getNumImages(true) <= 2) { logger.error(imageFile + " have " + reader.getNumImages(true) + " level. Trying to render thumbnail image from level 1"); page = reader.read(0); } else { page = reader.read(2); } if (page != null) { RenderedOp thubmnailImage = null; try { double resizeFactor = thumbnailWidth / page.getWidth(); if (resizeFactor <= 1) { ParameterBlock paramBlock = new ParameterBlock(); paramBlock.addSource(page); // The source image paramBlock.add(resizeFactor); // The xScale paramBlock.add(resizeFactor); // The yScale paramBlock.add(0.0); // The x translation paramBlock.add(0.0); // The y translation RenderingHints qualityHints = new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); thubmnailImage = JAI.create("SubsampleAverage", paramBlock, qualityHints); } else if (resizeFactor > 1) { thubmnailImage = ScaleDescriptor.create(page, (float) resizeFactor, (float) resizeFactor, 0.0f, 0.0f, Interpolation.getInstance(Interpolation.INTERP_BICUBIC), null); } if ((thumbnailFormat != null) && (thumbnailFormat.toLowerCase().equals("jpeg"))) { // replaced statement to control jpeg quality // ImageIO.write(thubmnailImage, "jpeg", // byteArrayOutputStream); JPEGEncodeParam jpgparam = new JPEGEncodeParam(); jpgparam.setQuality(imageQuality); ImageEncoder enc = ImageCodec.createImageEncoder("jpeg", byteArrayOutputStream, jpgparam); enc.encode(thubmnailImage); } else { logger.error("Unmanaged thumbnail format " + thumbnailFormat); } } catch (IOException ioException) { logger.error(ioException); } } // preparing image for output inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); // writing image to output httpServletResponse.setContentType("image/jpeg"); IOUtils.copy(inputStream, httpServletResponse.getOutputStream()); // Flushing request httpServletResponse.getOutputStream().flush(); } } else { logger.error("File " + imageFile.toString() + " is not present on filesystem."); } } catch (IIOException iioException) { if (iioException.getMessage().equals("Unsupported Image Type")) { logger.error("Unsupported Image Type " + imageFile); } else { logger.error(iioException); } } catch (IOException ioException) { logger.error(ioException); } finally { try { if (inputStream != null) { inputStream.close(); } } catch (IOException ioException) { } try { if (byteArrayOutputStream != null) { byteArrayOutputStream.close(); } } catch (IOException ioException) { } try { if (imageInputStream != null) { imageInputStream.close(); } } catch (IOException ioException) { } } }