List of usage examples for javax.imageio ImageReader dispose
public void dispose()
From source file:org.photovault.imginfo.ImageFile.java
/** * Opens the image file specified by fname & dirname properties, read * the rest of fields from that and create the instances * @param f File from which to read the information * @throws org.photovault.common.PhotovaultException If the file is not of recognized type * @throws IOException if the image cannot be read. *//*from www. ja v a 2s. co m*/ protected void readImageFile(File f) throws PhotovaultException, IOException { String fname = f.getName(); int lastDotPos = fname.lastIndexOf("."); if (lastDotPos <= 0 || lastDotPos >= fname.length() - 1) { throw new PhotovaultException("Cannot determine file type extension of " + f.getAbsolutePath()); } String suffix = fname.substring(lastDotPos + 1); Iterator readers = ImageIO.getImageReadersBySuffix(suffix); if (readers.hasNext()) { ImageReader reader = (ImageReader) readers.next(); ImageInputStream iis = null; try { iis = ImageIO.createImageInputStream(f); if (iis != null) { reader.setInput(iis, true); // int imageCount = reader.getNumImages( true ); // for now... int imageCount = 1; for (int n = 0; n < imageCount; n++) { ImageDescriptorBase img = new OriginalImageDescriptor(this, "image#" + n); img.setWidth(reader.getWidth(n)); img.setHeight(reader.getHeight(n)); // img.setInstanceType( ImageInstance.INSTANCE_TYPE_ORIGINAL ); img.setFile(this); } reader.dispose(); } } catch (IOException ex) { log.debug("Exception in readImageFile: " + ex.getMessage()); throw ex; } finally { if (iis != null) { try { iis.close(); } catch (IOException ex) { log.warn("Cannot close image stream: " + ex.getMessage()); } } } } else { RawImage ri = new RawImage(f); if (ri.isValidRawFile()) { // PlanarImage img = ri.getCorrectedImage(); ImageDescriptorBase img = new OriginalImageDescriptor(this, "image#0"); img.setWidth(ri.getWidth()); img.setHeight(ri.getHeight()); } else { throw new PhotovaultException( "Unknown image file extension " + suffix + "\nwhile reading " + f.getAbsolutePath()); } } }
From source file:uk.bl.wa.analyser.payload.FaceDetectionAnalyser.java
@Override public void analyse(String source, ArchiveRecordHeader header, InputStream tikainput, SolrRecord solr) { // Set up metadata object to pass to parsers: Metadata metadata = new Metadata(); // Skip large images: if (header.getLength() > max_size_bytes) { return;/* w w w . j av a2 s. co m*/ } // Only attempt to analyse a random sub-set of the data: // (prefixing with static test of a final value to allow JIT to fully // optimise out the "OR Math.random()" bit) if (sampleRate >= 1.0 || Math.random() < sampleRate) { // Increment number of images sampled: sampleCount++; // Attempt to extract faces etc.: if (this.extractFaces || this.extractDominantColours) { log.info("Attempting to parse image file: " + header.getUrl()); final long deepStart = System.nanoTime(); ParseRunner parser = new ParseRunner(fdp, tikainput, metadata, solr); try { TimeLimiter.run(parser, 30000L, false); } catch (Exception e) { log.error("WritableSolrRecord.extract(): " + e.getMessage()); solr.addParseException("when scanning for faces", e); } // Store basic image data: solr.addField(SolrFields.IMAGE_HEIGHT, metadata.get(FaceDetectionParser.IMAGE_HEIGHT)); solr.addField(SolrFields.IMAGE_WIDTH, metadata.get(FaceDetectionParser.IMAGE_WIDTH)); solr.addField(SolrFields.IMAGE_SIZE, metadata.get(FaceDetectionParser.IMAGE_SIZE)); if (this.extractFaces) { // Store faces in SOLR: for (String face : metadata.getValues(FaceDetectionParser.FACE_FRAGMENT_ID)) { log.debug("Found a face!"); solr.addField(SolrFields.IMAGE_FACES, face); } int faces = metadata.getValues(FaceDetectionParser.FACE_FRAGMENT_ID).length; if (faces > 0) solr.setField(SolrFields.IMAGE_FACES_COUNT, "" + faces); } if (this.extractDominantColours) { // Store colour: solr.addField(SolrFields.IMAGE_DOMINANT_COLOUR, metadata.get(FaceDetectionParser.DOM_COL)); // TODO Extract multiple characteristic colours as well } Instrument.timeRel("WARCPayloadAnalyzers.analyze#total", "ImageAnalyzer.analyze#facesanddominant", deepStart); } else { //images are enabled, we still want to extract image/height (fast) //This method takes 0.2ms for a large image. I can be done even faster if needed(but more complicated)). //see https://stackoverflow.com/questions/672916/how-to-get-image-height-and-width-using-java ImageInputStream input = null; ImageReader reader = null; try { input = ImageIO.createImageInputStream(tikainput); reader = ImageIO.getImageReaders(input).next(); reader.setInput(input); // Get dimensions of first image in the stream, without decoding pixel values int width = reader.getWidth(0); int height = reader.getHeight(0); // Store basic image data: solr.addField(SolrFields.IMAGE_HEIGHT, "" + height); solr.addField(SolrFields.IMAGE_WIDTH, "" + width); solr.addField(SolrFields.IMAGE_SIZE, "" + (height * width)); } catch (Exception e) { //it is known that (most) .ico and (all) .svg are not supported by java. Do not log, since it will spam. log.warn("Unable to extract image data for url:" + header.getUrl(), e); } finally { if (reader != null) { reader.dispose(); } } } } }
From source file:sernet.verinice.service.commands.LoadAttachmentFile.java
private BufferedImage readImageFromByteArrayFallback() throws IOException { ImageInputStream in = ImageIO .createImageInputStream(new ByteArrayInputStream(getAttachmentFile().getFileData())); Iterator<ImageReader> iter = ImageIO.getImageReaders(in); BufferedImage image = null;/*from w w w . ja v a2 s .c o m*/ while (iter.hasNext()) { ImageReader reader = null; try { reader = (ImageReader) iter.next(); ImageReadParam param = reader.getDefaultReadParam(); reader.setInput(in, true, true); Iterator<ImageTypeSpecifier> imageTypes = reader.getImageTypes(0); while (imageTypes.hasNext()) { ImageTypeSpecifier imageTypeSpecifier = imageTypes.next(); int bufferedImageType = imageTypeSpecifier.getBufferedImageType(); if (bufferedImageType == BufferedImage.TYPE_BYTE_GRAY) { param.setDestinationType(imageTypeSpecifier); break; } } image = reader.read(0, param); if (null != image) { break; } } catch (Exception e) { getLog().error("Error while reading image the advanced way. DbId: " + getAttachmentFile().getDbId(), e); } finally { if (null != reader) { reader.dispose(); } } } return image; }
From source file:org.geotools.coverage.io.util.Utilities.java
/** * Returns a {@code PlanarImage} given a set of parameter specifying the type of read operation to be performed. * /*w w w . jav a 2s .c o m*/ * @param imageIndex * * @param new FileImageInputStreamExtImplinput the input {@code ImageInputStream} to be used for reading the image. * @param useJAI {@code true} if we need to use a JAI ImageRead operation, {@code false} if we need a simple direct {@code ImageReader.read(...)} * call. * @param imageReadParam an {@code ImageReadParam} specifying the read parameters * @param useMultithreading {@code true} if a JAI ImageRead operation is requested with support for multithreading. This parameter will be ignored * if requesting a direct read operation. * @return the read {@code PlanarImage} * @throws IOException */ public static PlanarImage readImage(final ImageReaderSpi spi, final Object input, final int imageIndex, final boolean useJAI, final ImageReadParam imageReadParam, final boolean useMultithreading) throws IOException { ImageInputStream paramInput = null; if (input instanceof File) { paramInput = new FileImageInputStreamExtImpl((File) input); } else if (input instanceof FileImageInputStreamExt) { paramInput = (FileImageInputStreamExt) input; } else if (input instanceof URIImageInputStream) { paramInput = (URIImageInputStream) input; } else if (input instanceof URL) { final URL tempURL = (URL) input; String protocol = tempURL.getProtocol(); if (protocol.equalsIgnoreCase("file")) { try { File file = it.geosolutions.imageio.utilities.Utilities.urlToFile(tempURL); paramInput = new FileImageInputStreamExtImpl(file); } catch (IOException e) { throw new RuntimeException("Failed to create a valid input stream ", e); } } else if (tempURL.getProtocol().toLowerCase().startsWith("http") || tempURL.getProtocol().equalsIgnoreCase("dods")) { try { paramInput = new URIImageInputStreamImpl(tempURL.toURI()); } catch (URISyntaxException e) { throw new RuntimeException("Failed to create a valid input stream ", e); } } } else throw new IllegalArgumentException("Unsupported Input type:" + input); PlanarImage planarImage; ImageReader reader; ImageReaderSpi readerSpi = spi; if (useJAI) { final ParameterBlock pbjImageRead = new ParameterBlock(); pbjImageRead.add(paramInput); pbjImageRead.add(imageIndex); pbjImageRead.add(Boolean.FALSE); pbjImageRead.add(Boolean.FALSE); pbjImageRead.add(Boolean.FALSE); pbjImageRead.add(null); pbjImageRead.add(null); pbjImageRead.add(imageReadParam); reader = readerSpi.createReaderInstance(); pbjImageRead.add(reader); // Check if to use a simple JAI ImageRead operation or a // multithreaded one final String jaiOperation = useMultithreading ? "ImageReadMT" : "ImageRead"; // final String jaiOperation = "ImageRead"; /** TODO: SET HINTS */ planarImage = JAI.create(jaiOperation, pbjImageRead, null); } else { reader = readerSpi.createReaderInstance(); reader.setInput(paramInput, true, true); planarImage = PlanarImage.wrapRenderedImage(reader.read(imageIndex, imageReadParam)); reader.dispose(); } return planarImage; }
From source file:org.xwiki.contrib.ldap.XWikiLDAPUtils.java
/** * Guess image type of InputStream.//from www. j a v a 2s . 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.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 2 s . 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.apache.pdfbox.tools.imageio.TestImageIOUtils.java
/** * checks whether the resolution of an image file is as expected. * * @param filename the name of the file//from w w w. j av a 2s . c om * @param expectedResolution the expected resolution * * @throws IOException if something goes wrong */ private void checkResolution(String filename, int expectedResolution) throws IOException { assertFalse("Empty file " + filename, new File(filename).length() == 0); String suffix = filename.substring(filename.lastIndexOf('.') + 1); if ("BMP".equals(suffix.toUpperCase())) { // BMP reader doesn't work checkBmpResolution(filename, expectedResolution); return; } Iterator readers = ImageIO.getImageReadersBySuffix(suffix); assertTrue("No image reader found for suffix " + suffix, readers.hasNext()); ImageReader reader = (ImageReader) readers.next(); ImageInputStream iis = ImageIO.createImageInputStream(new File(filename)); assertNotNull("No ImageInputStream created for file " + filename, iis); reader.setInput(iis); IIOMetadata imageMetadata = reader.getImageMetadata(0); Element root = (Element) imageMetadata.getAsTree(STANDARD_METADATA_FORMAT); NodeList dimensionNodes = root.getElementsByTagName("Dimension"); assertTrue("No resolution found in image file " + filename, dimensionNodes.getLength() > 0); Element dimensionElement = (Element) dimensionNodes.item(0); NodeList pixelSizeNodes = dimensionElement.getElementsByTagName("HorizontalPixelSize"); assertTrue("No X resolution found in image file " + filename, pixelSizeNodes.getLength() > 0); Node pixelSizeNode = pixelSizeNodes.item(0); String val = pixelSizeNode.getAttributes().getNamedItem("value").getNodeValue(); int actualResolution = (int) Math.round(25.4 / Double.parseDouble(val)); assertEquals("X resolution doesn't match in image file " + filename, expectedResolution, actualResolution); pixelSizeNodes = dimensionElement.getElementsByTagName("VerticalPixelSize"); assertTrue("No Y resolution found in image file " + filename, pixelSizeNodes.getLength() > 0); pixelSizeNode = pixelSizeNodes.item(0); val = pixelSizeNode.getAttributes().getNamedItem("value").getNodeValue(); actualResolution = (int) Math.round(25.4 / Double.parseDouble(val)); assertEquals("Y resolution doesn't match", expectedResolution, actualResolution); iis.close(); reader.dispose(); }
From source file:org.olat.core.commons.services.image.spi.ImageHelperImpl.java
private static SizeAndBufferedImage calcScaledSize(ImageInputStream stream, String suffix, int maxWidth, int maxHeight, boolean fill) { Iterator<ImageReader> iter = ImageIO.getImageReadersBySuffix(suffix); if (iter.hasNext()) { ImageReader reader = iter.next(); try {/* w w w . ja va 2 s. c o m*/ reader.setInput(stream, true, true); int width = reader.getWidth(reader.getMinIndex()); int height = reader.getHeight(reader.getMinIndex()); Size size = new Size(width, height, false); Size scaledSize = computeScaledSize(width, height, maxWidth, maxHeight, fill); SizeAndBufferedImage all = new SizeAndBufferedImage(size, scaledSize); int readerMinIndex = reader.getMinIndex(); ImageReadParam param = reader.getDefaultReadParam(); Iterator<ImageTypeSpecifier> imageTypes = reader.getImageTypes(0); while (imageTypes.hasNext()) { try { ImageTypeSpecifier imageTypeSpecifier = imageTypes.next(); int bufferedImageType = imageTypeSpecifier.getBufferedImageType(); if (bufferedImageType == BufferedImage.TYPE_BYTE_GRAY) { param.setDestinationType(imageTypeSpecifier); } double memoryKB = (width * height * 4) / 1024d; if (memoryKB > 2000) {// check limit at 20MB double free = Runtime.getRuntime().freeMemory() / 1024d; if (free > memoryKB) { all.setImage(reader.read(readerMinIndex, param)); } else { // make sub sampling to save memory int ratio = (int) Math.round(Math.sqrt(memoryKB / free)); param.setSourceSubsampling(ratio, ratio, 0, 0); all.setImage(reader.read(readerMinIndex, param)); } } else { all.setImage(reader.read(readerMinIndex, param)); } return all; } catch (IllegalArgumentException e) { log.warn(e.getMessage(), e); } } } catch (IOException e) { log.error(e.getMessage(), e); } finally { reader.dispose(); } } else { log.error("No reader found for given format: " + suffix, null); } return null; }
From source file:nl.b3p.imagetool.ImageTool.java
/** * Reads an image from an http input stream. * * @param method Apache HttpClient GetMethod object * @param mime String representing the mime type of the image. * * @return BufferedImage/*from w w w. j av a2 s . c o m*/ * * @throws Exception */ // <editor-fold defaultstate="" desc="readImage(GetMethod method, String mime) method."> public static BufferedImage readImage(InputStream is, String mime) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); int bytesRead = 0; byte[] buffer = new byte[2048]; while (bytesRead != -1) { bytesRead = is.read(buffer, 0, buffer.length); if (bytesRead > 0) { baos.write(buffer, 0, bytesRead); } } ImageReader ir = null; BufferedImage i = null; try { if (mime.indexOf(";") != -1) { mime = mime.substring(0, mime.indexOf(";")); } String mimeType = getMimeType(mime); /* TODO: Kijken waarom er geen mime type meer binnenkomt. Wellicht door de * HttpClient vernieuwing in kaartenbalie ? */ if (mimeType == null) { mimeType = "image/png"; } if (mimeType == null) { log.error("Response from server not understood (mime = " + mime + "): " + baos.toString()); throw new Exception( "Response from server not understood (mime = " + mime + "): " + baos.toString()); } ir = getReader(mimeType); if (ir == null) { log.error("no reader available for imageformat: " + mimeType.substring(mimeType.lastIndexOf("/") + 1)); throw new Exception("no reader available for imageformat: " + mimeType.substring(mimeType.lastIndexOf("/") + 1)); } //TODO Make smarter.. Possibly faster... But keep reporting! ImageInputStream stream = ImageIO.createImageInputStream(new ByteArrayInputStream(baos.toByteArray())); ir.setInput(stream, true); i = ir.read(0); //if image is a png, has no alpha and has a tRNS then make that color transparent. if (!i.getColorModel().hasAlpha() && ir.getImageMetadata(0) instanceof PNGMetadata) { PNGMetadata metadata = (PNGMetadata) ir.getImageMetadata(0); if (metadata.tRNS_present) { int alphaPix = (metadata.tRNS_red << 16) | (metadata.tRNS_green << 8) | (metadata.tRNS_blue); BufferedImage tmp = new BufferedImage(i.getWidth(), i.getHeight(), BufferedImage.TYPE_INT_ARGB); for (int x = 0; x < i.getWidth(); x++) { for (int y = 0; y < i.getHeight(); y++) { int rgb = i.getRGB(x, y); rgb = (rgb & 0xFFFFFF) == alphaPix ? alphaPix : rgb; tmp.setRGB(x, y, rgb); } } i = tmp; } } } finally { if (ir != null) { ir.dispose(); } } return i; }
From source file:org.dita.dost.writer.ImageMetadataFilter.java
private Attributes readMetadata(final URI imgInput) { logger.info("Reading " + imgInput); final XMLUtils.AttributesBuilder a = new XMLUtils.AttributesBuilder(); try {// ww w . j a va2 s . c o m InputStream in = null; ImageReader r = null; ImageInputStream iis = null; try { in = getInputStream(imgInput); iis = ImageIO.createImageInputStream(in); final Iterator<ImageReader> i = ImageIO.getImageReaders(iis); if (!i.hasNext()) { logger.info("Image " + imgInput + " format not supported"); } else { r = i.next(); r.setInput(iis); final int imageIndex = r.getMinIndex(); a.add(DITA_OT_NS, ATTR_IMAGE_WIDTH, DITA_OT_PREFIX + ":" + ATTR_IMAGE_WIDTH, "CDATA", Integer.toString(r.getWidth(imageIndex))); a.add(DITA_OT_NS, ATTR_IMAGE_HEIGHT, DITA_OT_PREFIX + ":" + ATTR_IMAGE_HEIGHT, "CDATA", Integer.toString(r.getHeight(imageIndex))); final Element node = (Element) r.getImageMetadata(0).getAsTree("javax_imageio_1.0"); final NodeList hs = node.getElementsByTagName("HorizontalPixelSize"); if (hs != null && hs.getLength() == 1) { final float v = Float.parseFloat(((Element) hs.item(0)).getAttribute("value")); final int dpi = Math.round(MM_TO_INCH / v); a.add(DITA_OT_NS, ATTR_HORIZONTAL_DPI, DITA_OT_PREFIX + ":" + ATTR_HORIZONTAL_DPI, "CDATA", Integer.toString(dpi)); } final NodeList vs = node.getElementsByTagName("VerticalPixelSize"); if (vs != null && vs.getLength() == 1) { final float v = Float.parseFloat(((Element) vs.item(0)).getAttribute("value")); final int dpi = Math.round(MM_TO_INCH / v); a.add(DITA_OT_NS, ATTR_VERTICAL_DPI, DITA_OT_PREFIX + ":" + ATTR_VERTICAL_DPI, "CDATA", Integer.toString(dpi)); } } } finally { if (r != null) { r.dispose(); } if (iis != null) { iis.close(); } if (in != null) { in.close(); } } } catch (final Exception e) { logger.error("Failed to read image " + imgInput + " metadata: " + e.getMessage(), e); } return a.build(); }