List of usage examples for javax.imageio ImageReader getHeight
public abstract int getHeight(int imageIndex) throws IOException;
From source file:org.photovault.image.ImageIOImage.java
/** Load the image and/or metadata//from w w w . j ava 2s . c o m @param loadImage Load the image pixel data if <CODE>true</CODE> @param loadMetadata Load image metadata if <CODE>true</CODE>. @param minWidth Minimum width of the loaded image @param minHeight Minimum height of the loaded image @param isLowQualityAllowed If <code>true</code>, use larger subsampling to speed up loading. */ private void load(boolean loadImage, boolean loadMetadata, int minWidth, int minHeight, boolean isLowQualityAllowed) { if (f != null && f.canRead()) { ImageReader reader = getImageReader(f); if (reader != null) { log.debug("Creating stream"); ImageInputStream iis = null; try { iis = ImageIO.createImageInputStream(f); reader.setInput(iis, false, false); width = reader.getWidth(0); height = reader.getHeight(0); if (loadImage) { RenderedImage ri = null; if (isLowQualityAllowed) { ri = readExifThumbnail(f); if (ri == null || !isOkForThumbCreation(ri.getWidth(), ri.getHeight(), minWidth, minHeight, reader.getAspectRatio(0), 0.01)) { /* EXIF thumbnail either did not exist or was unusable, try to read subsampled version of original */ ri = readSubsampled(reader, minWidth, minHeight); } } else { /* High quality image is requested. If the image is very large, use subsampling anyway to decrease memory consumption & speed up interactive operations. Anyway, most often user just views image at screen resolution */ ImageReadParam param = reader.getDefaultReadParam(); if (minWidth * 2 < width && minHeight * 2 < height) { param.setSourceSubsampling(2, 2, 0, 0); } ri = reader.read(0, param); } if (ri != null) { /* TODO: JAI seems to have problems in doing convolutions for large image tiles. Split image to reasonably sized tiles as a workaround for this. */ ri = new TiledImage(ri, 256, 256); image = new RenderedImageAdapter(ri); originalSampleModel = image.getSampleModel(); originalColorModel = image.getColorModel(); final float[] DEFAULT_KERNEL_1D = { 0.25f, 0.5f, 0.25f }; ParameterBlock pb = new ParameterBlock(); KernelJAI kernel = new KernelJAI(DEFAULT_KERNEL_1D.length, DEFAULT_KERNEL_1D.length, DEFAULT_KERNEL_1D.length / 2, DEFAULT_KERNEL_1D.length / 2, DEFAULT_KERNEL_1D, DEFAULT_KERNEL_1D); pb.add(kernel); BorderExtender extender = BorderExtender.createInstance(BorderExtender.BORDER_COPY); RenderingHints hints = JAI.getDefaultInstance().getRenderingHints(); if (hints == null) { hints = new RenderingHints(JAI.KEY_BORDER_EXTENDER, extender); } else { hints.put(JAI.KEY_BORDER_EXTENDER, extender); } RenderedOp filter = new RenderedOp("convolve", pb, hints); // javax.media.jai.operator.BoxFilterDescriptor.create( null, new Integer(2), new Integer(2), new Integer(0), new Integer(0), null ); // Add the subsampling operation. pb = new ParameterBlock(); pb.addSource(filter); pb.add(new Float(0.5F)).add(new Float(0.5F)); pb.add(new Float(0.0F)).add(new Float(0.0F)); pb.add(Interpolation.getInstance(Interpolation.INTERP_NEAREST)); RenderedOp downSampler = new RenderedOp("scale", pb, null); renderableImage = RenderableDescriptor.createRenderable(image, downSampler, null, null, null, null, null); } else { image = null; renderableImage = null; } imageIsLowQuality = isLowQualityAllowed; } if (loadMetadata) { readImageMetadata(reader); } } catch (Exception ex) { log.warn(ex.getMessage()); ex.printStackTrace(); return; } } } }
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 .j a v a 2s . 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; }
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. */// w w w .ja v a 2 s. c om 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:se.trixon.almond.GraphicsHelper.java
public static Dimension getImgageDimension(File imageFile) throws IOException { ImageInputStream inputStream = ImageIO.createImageInputStream(imageFile); try {/* w ww .jav a 2 s . com*/ final Iterator<ImageReader> imageReaders = ImageIO.getImageReaders(inputStream); if (imageReaders.hasNext()) { ImageReader imageReader = imageReaders.next(); try { imageReader.setInput(inputStream); return new Dimension(imageReader.getWidth(0), imageReader.getHeight(0)); } finally { imageReader.dispose(); } } } finally { if (inputStream != null) { inputStream.close(); } } return null; }
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;/*from ww w . j a v a2 s . c o 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:uk.bl.wa.analyser.payload.ImageAnalyser.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;/*from w w w .j a va 2 s . c om*/ } // 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++; // 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 height/width/size for url:"+header.getUrl(),e); } finally { if (reader != null) { reader.dispose(); } } } }