List of usage examples for javax.imageio ImageReader getFormatName
public String getFormatName() throws IOException
From source file:com.occamlab.te.parsers.ImageParser.java
private static Document parse(InputStream source, Element instruction, PrintWriter logger) throws Exception { ImageReader reader; try {// ww w . j a v a 2 s. c o m 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.utils.imageoverviews.OverviewsEmbedder.java
public void run() { // did we create a local private tile cache or not? boolean localTileCache = false; //// w w w . j a v a2 s . c o m // creating the image to use for the successive // subsampling // TileCache baseTC = JAI.getDefaultInstance().getTileCache(); if (baseTC == null) { localTileCache = true; final long tilecacheSize = super.getTileCacheSize(); baseTC = JAI.createTileCache(); baseTC.setMemoryCapacity(tilecacheSize); baseTC.setMemoryThreshold(0.75f); } // // CHECK INPUT DIRECTORIES/FILES // if (sourcePath == null) { fireEvent("Provided sourcePath is null", overallProgress); return; } // getting an image input stream to the file final File file = new File(sourcePath); final File[] files; int numFiles = 1; StringBuilder message; if (!file.canRead() || !file.exists()) { fireEvent("Provided file " + file.getAbsolutePath() + " cannot be read or does not exist", 100); return; } if (file.isDirectory()) { if (wildcardString == null) { fireEvent("Provided wildcardString is null", 100); return; } final FileFilter fileFilter = new WildcardFileFilter(wildcardString); files = file.listFiles(fileFilter); numFiles = files.length; if (numFiles <= 0) { message = new StringBuilder("No files to process!"); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine(message.toString()); } fireEvent(message.toString(), 100); } } else files = new File[] { file }; if (files == null || files.length == 0) { fireEvent("Unable to find input files for the provided wildcard " + wildcardString + " and input path " + sourcePath, 100); return; } // setting step overallProgressStep = 100 * 1.0 / numFiles; // // ADDING OVERVIEWS TO ALL FOUND FILES // for (fileBeingProcessed = 0; fileBeingProcessed < numFiles; fileBeingProcessed++) { message = new StringBuilder("Managing file ").append(fileBeingProcessed).append(" of ") .append(files[fileBeingProcessed]).append(" files"); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine(message.toString()); } overallProgress = overallProgressStep * fileBeingProcessed; fireEvent(message.toString(), overallProgress); if (getStopThread()) { message = new StringBuilder("Stopping requested at file ").append(fileBeingProcessed) .append(" of ").append(numFiles).append(" files"); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine(message.toString()); } fireEvent(message.toString(), overallProgress); return; } ImageInputStream stream = null; ImageWriter writer = null; ImageOutputStream streamOut = null; RenderedOp currentImage = null; RenderedOp newImage = null; try { File localFile = files[fileBeingProcessed]; // // get a stream // stream = ImageIO.createImageInputStream(localFile); if (stream == null) { message = new StringBuilder("Unable to create an input stream for file") .append(files[fileBeingProcessed]); if (LOGGER.isLoggable(Level.SEVERE)) { LOGGER.severe(message.toString()); } fireEvent(message.toString(), overallProgress); break; } stream.mark(); // // get a reader // final Iterator<ImageReader> it = ImageIO.getImageReaders(stream); if (!it.hasNext()) { message = new StringBuilder("Unable to find a reader for file") .append(files[fileBeingProcessed]); if (LOGGER.isLoggable(Level.SEVERE)) { LOGGER.severe(message.toString()); } fireEvent(message.toString(), overallProgress); break; } final ImageReader reader = (ImageReader) it.next(); stream.reset(); stream.mark(); // is it a geotiff reader or not? if (!reader.getFormatName().toLowerCase().startsWith("tif")) { if (LOGGER.isLoggable(Level.INFO)) { LOGGER.info("Discarding input file " + files[fileBeingProcessed] + " since it is not a proper tif file."); } continue; } // // set input // reader.setInput(stream); ImageLayout layout = null; // tiling the image if needed int actualTileW = reader.getTileWidth(0); int actualTileH = reader.getTileHeight(0); if (!reader.isImageTiled(0) || (reader.isImageTiled(0) && (actualTileH != tileH && tileH != -1) || (actualTileW != tileW && tileW != -1))) { message = new StringBuilder("Retiling image ").append(fileBeingProcessed); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine(message.toString()); } fireEvent(message.toString(), overallProgress); layout = Utils.createTiledLayout(tileW, tileH, 0, 0); } stream.reset(); reader.reset(); reader.dispose(); // // output image stream // if (externalOverviews) { // create a sibling file localFile = new File(localFile.getParent(), FilenameUtils.getBaseName(localFile.getAbsolutePath()) + ".tif.ovr"); } streamOut = ImageIOExt.createImageOutputStream(null, localFile); if (streamOut == null) { message = new StringBuilder("Unable to acquire an ImageOutputStream for the file ") .append(files[fileBeingProcessed].toString()); if (LOGGER.isLoggable(Level.SEVERE)) { LOGGER.severe(message.toString()); } fireEvent(message.toString(), 100); break; } // // Preparing to write the set of images. First of all I write // the first image ` // // getting a writer for this reader writer = TIFF_IMAGE_WRITER_SPI.createWriterInstance(); writer.setOutput(streamOut); writer.addIIOWriteProgressListener(writeProgressListener); writer.addIIOWriteWarningListener(writeProgressListener); ImageWriteParam param = writer.getDefaultWriteParam(); // // setting tiling on the first image using writing parameters // if (tileH != -1 & tileW != -1) { param.setTilingMode(ImageWriteParam.MODE_EXPLICIT); param.setTiling(tileW, tileH, 0, 0); } else { param.setTilingMode(ImageWriteParam.MODE_EXPLICIT); param.setTiling(actualTileW, actualTileH, 0, 0); } if (this.compressionScheme != null && !Double.isNaN(compressionRatio)) { param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); param.setCompressionType(compressionScheme); param.setCompressionQuality((float) this.compressionRatio); } final RenderingHints newHints = new RenderingHints(JAI.KEY_IMAGE_LAYOUT, layout); newHints.add(new RenderingHints(JAI.KEY_TILE_CACHE, baseTC)); // read base image ParameterBlock pbjRead = new ParameterBlock(); pbjRead.add(stream); pbjRead.add(Integer.valueOf(0)); pbjRead.add(Boolean.FALSE); pbjRead.add(Boolean.FALSE); pbjRead.add(Boolean.FALSE); pbjRead.add(null); pbjRead.add(null); pbjRead.add(null); pbjRead.add(null); currentImage = JAI.create("ImageRead", pbjRead, newHints); message = new StringBuilder("Read original image ").append(fileBeingProcessed); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine(message.toString()); } fireEvent(message.toString(), overallProgress); int i = 0; // // OVERVIEWS CYLE // for (overviewInProcess = 0; overviewInProcess < numSteps; overviewInProcess++) { message = new StringBuilder("Subsampling step ").append(overviewInProcess + 1) .append(" of image ").append(fileBeingProcessed); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine(message.toString()); } fireEvent(message.toString(), overallProgress); // paranoiac check if (currentImage.getWidth() / downsampleStep <= 0 || currentImage.getHeight() / downsampleStep <= 0) break; // SCALE // subsampling the input image using the chosen algorithm final SubsampleAlgorithm algorithm = SubsampleAlgorithm.valueOf(scaleAlgorithm); switch (algorithm) { case Average: newImage = Utils.scaleAverage(currentImage, baseTC, downsampleStep, borderExtender); break; case Filtered: newImage = Utils.filteredSubsample(currentImage, baseTC, downsampleStep, lowPassFilter); break; case Bilinear: newImage = Utils.subsample(currentImage, baseTC, new InterpolationBilinear(), downsampleStep, borderExtender); break; case Bicubic: newImage = Utils.subsample(currentImage, baseTC, new InterpolationBicubic(2), downsampleStep, borderExtender); break; case Nearest: newImage = Utils.subsample(currentImage, baseTC, new InterpolationNearest(), downsampleStep, borderExtender); break; default: throw new IllegalArgumentException("Invalid scaling algorithm " + scaleAlgorithm);//cannot get here } //set relevant metadata IIOMetadata imageMetadata = null; if (writer instanceof TIFFImageWriter) { imageMetadata = writer.getDefaultImageMetadata(new ImageTypeSpecifier(newImage), param); if (imageMetadata != null) ((TIFFImageMetadata) imageMetadata).addShortOrLongField( BaselineTIFFTagSet.TAG_NEW_SUBFILE_TYPE, BaselineTIFFTagSet.NEW_SUBFILE_TYPE_REDUCED_RESOLUTION); } // write out if (!externalOverviews || i > 0) writer.writeInsert(-1, new IIOImage(newImage, null, imageMetadata), param); else writer.write(null, new IIOImage(newImage, null, imageMetadata), param); message = new StringBuilder("Step ").append(overviewInProcess + 1).append(" of image ") .append(fileBeingProcessed).append(" done!"); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine(message.toString()); } fireEvent(message.toString(), overallProgress); // switching images currentImage.dispose(); //dispose old image currentImage = newImage; i++; } overallProgress = 100; // close message message = new StringBuilder("Done with image ").append(fileBeingProcessed); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine(message.toString()); } fireEvent(message.toString(), overallProgress); } catch (Throwable e) { fireException(e); } finally { // clean up // clean caches if they are local if (localTileCache && baseTC != null) try { baseTC.flush(); } catch (Exception e) { } // // free everything try { if (streamOut != null) streamOut.close(); } catch (Throwable e) { if (LOGGER.isLoggable(Level.FINE)) LOGGER.log(Level.FINE, e.getLocalizedMessage(), e); } try { if (writer != null) writer.dispose(); } catch (Throwable e) { if (LOGGER.isLoggable(Level.FINE)) LOGGER.log(Level.FINE, e.getLocalizedMessage(), e); } try { if (currentImage != null) currentImage.dispose(); } catch (Throwable e) { if (LOGGER.isLoggable(Level.FINE)) LOGGER.log(Level.FINE, e.getLocalizedMessage(), e); } try { if (newImage != null) newImage.dispose(); } catch (Throwable e) { if (LOGGER.isLoggable(Level.FINE)) LOGGER.log(Level.FINE, e.getLocalizedMessage(), e); } try { if (stream != null) stream.close(); } catch (Throwable e) { if (LOGGER.isLoggable(Level.FINE)) LOGGER.log(Level.FINE, e.getLocalizedMessage(), e); } } } if (LOGGER.isLoggable(Level.FINE)) LOGGER.fine("Done!!!"); }
From source file:com.evolveum.polygon.connector.drupal.DrupalConnector.java
private String createFile(byte[] fileContent, String fileName) throws IOException { // determine image type String extension = "jpg"; try {/*w w w . j a va2 s .c o m*/ ByteArrayInputStream is = new ByteArrayInputStream(fileContent); ImageInputStream iis = ImageIO.createImageInputStream(is); Iterator<ImageReader> imageReaders = ImageIO.getImageReaders(iis); while (imageReaders.hasNext()) { ImageReader reader = (ImageReader) imageReaders.next(); extension = reader.getFormatName(); } } catch (IOException e) { throw new ConnectorIOException("not parseable image extension (JPEG/PNG/...): " + e.getMessage(), e); } JSONObject jo = new JSONObject(); jo.put(ATTR_FILE_STATUS, ATTR_FILE_STATUS_DEFAULT); jo.put(ATTR_FILE_FILE, Base64.encode(fileContent)); jo.put(ATTR_FILE_FILENAME, fileName + "." + extension); HttpPost request = new HttpPost(getConfiguration().getServiceAddress() + FILE); JSONObject file = callRequest(request, jo); return file.getString(FID); }
From source file:org.xwiki.contrib.ldap.XWikiLDAPUtils.java
/** * Guess image type of InputStream./*w w w . java 2 s. c o m*/ * * @param imageInputStream InputStream containing image. * @return type of image as String. */ protected String guessImageType(InputStream imageInputStream) { ImageInputStream imageStream; try { imageStream = ImageIO.createImageInputStream(imageInputStream); } catch (IOException ex) { LOGGER.error(ex.getMessage()); return null; } Iterator<ImageReader> it = ImageIO.getImageReaders(imageStream); if (!it.hasNext()) { LOGGER.warn("No image readers found for provided stream."); return null; } ImageReader imageReader = it.next(); imageReader.setInput(imageStream); try { return imageReader.getFormatName(); } catch (IOException ex) { LOGGER.error(ex.getMessage()); return null; } finally { imageReader.dispose(); } }
From source file:org.photovault.image.ImageIOImage.java
/** Read the image (either original or proper thumbnail in the same file and subsample it to save memory & time. The image is subsampled so that its reasolution is the smallest possible that is bigger than given limits. /* w ww . jav a2 s . c o m*/ @param reader The image reader that is used for reading the image @param minWidth Minimum width of the subsampled image @param minHeight Minimum height of the subsampled iamge @return Subsampled image. */ private RenderedImage readSubsampled(ImageReader reader, int minWidth, int minHeight) throws IOException { /* We try to ensure that the thumbnail is actually from the original image by comparing aspect ratio of it to original. This is not a perfect check but it will usually catch the most typical errors (like having a the original rotated by RAW conversion SW but still the original EXIF thumbnail. */ double origAspect = reader.getAspectRatio(0); double aspectAccuracy = 0.01; int minInstanceSide = Math.max(minWidth, minHeight); int numThumbs = 0; RenderedImage image = null; try { int numImages = reader.getNumImages(true); if (numImages > 0) { numThumbs = reader.getNumThumbnails(0); } } catch (IOException ex) { ex.printStackTrace(); } if (numThumbs > 0 && isOkForThumbCreation(reader.getThumbnailWidth(0, 0), reader.getThumbnailHeight(0, 0), minWidth, minHeight, origAspect, aspectAccuracy)) { // There is a thumbanil that is big enough - use it log.debug("Original has thumbnail, size " + reader.getThumbnailWidth(0, 0) + " x " + reader.getThumbnailHeight(0, 0)); image = reader.readThumbnail(0, 0); log.debug("Read thumbnail"); } else { log.debug("No thumbnail in original"); ImageReadParam param = reader.getDefaultReadParam(); // Find the maximum subsampling rate we can still use for creating // a quality thumbnail. Some image format readers seem to have // problems with subsampling values (e.g. PNG sometimes crashed // the whole virtual machine, to for now let's do this only // with JPG. int subsampling = 1; if (reader.getFormatName().equals("JPEG")) { int minDim = Math.min(reader.getWidth(0), reader.getHeight(0)); while (2 * minInstanceSide * subsampling < minDim) { subsampling *= 2; } } param.setSourceSubsampling(subsampling, subsampling, 0, 0); image = reader.read(0, param); } return image; }