List of usage examples for javax.imageio ImageReader setInput
public void setInput(Object input, boolean seekForwardOnly, boolean ignoreMetadata)
From source file:Main.java
public static void main(String[] argv) throws Exception { ImageInputStream imageStream = ImageIO.createImageInputStream(new URL("").openStream()); Iterator<ImageReader> readers = ImageIO.getImageReaders(imageStream); ImageReader reader = null; if (!readers.hasNext()) { imageStream.close();/*from w ww . ja v a 2s . com*/ return; } else { reader = readers.next(); } String formatName = reader.getFormatName(); if (!formatName.equalsIgnoreCase("jpeg") && !formatName.equalsIgnoreCase("png") && !formatName.equalsIgnoreCase("gif")) { imageStream.close(); return; } reader.setInput(imageStream, true, true); BufferedImage theImage = reader.read(0); reader.dispose(); imageStream.close(); }
From source file:Main.java
public static BufferedImage readFragment(InputStream stream, Rectangle rect) throws IOException { ImageInputStream imageStream = ImageIO.createImageInputStream(stream); ImageReader reader = ImageIO.getImageReaders(imageStream).next(); ImageReadParam param = reader.getDefaultReadParam(); param.setSourceRegion(rect);//from www . jav a 2s . co m reader.setInput(imageStream, true, true); BufferedImage image = reader.read(0, param); reader.dispose(); imageStream.close(); return image; }
From source file:common.utils.ImageUtils.java
/** * closes iis/*from w w w .ja va2s. c o m*/ * @param iis * @return image from given stream or null if no readers found * @throws java.io.IOException */ public static BufferedImageHolder readImage(ImageInputStream iis) throws IOException { ImageReader reader = getImageReader(iis); if (reader == null) { iis.close(); return null; } reader.setInput(iis, true, true); ImageReadParam param = reader.getDefaultReadParam(); String format_name = reader.getFormatName(); BufferedImage bi; try { bi = reader.read(0, param); } finally { reader.dispose(); iis.close(); } return new BufferedImageHolder(bi, format_name); }
From source file:org.olat.core.commons.services.image.spi.ImageHelperImpl.java
private static SizeAndBufferedImage getImage(ImageInputStream stream, String suffix) { Iterator<ImageReader> iter = ImageIO.getImageReadersBySuffix(suffix); if (iter.hasNext()) { ImageReader reader = iter.next(); try {/*from w w w. j a va 2s . 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); SizeAndBufferedImage all = new SizeAndBufferedImage(size, null); 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); } 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: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 {/*from w w w .j a v a2 s . c om*/ 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:org.jimcat.services.imagemanager.ImageUtil.java
/** * get an image reader for the given file content * //from w w w .jav a 2 s . c om * @param image * @return an image reader for the given content * @throws IOException */ private static ImageReader getReaderForImage(byte image[]) throws IOException { // resolve image using ImageIO stream ImageInputStream stream = ImageIO.createImageInputStream(new ByteArrayInputStream(image)); // check if there is an image inside the stream Iterator iter = ImageIO.getImageReaders(stream); if (!iter.hasNext()) { // none found return null; } // setup reader ImageReader reader = (ImageReader) iter.next(); reader.setInput(stream, true, true); return reader; }
From source file:org.carcv.core.model.file.FileCarImage.java
/** * Reads a rectangular region from an image in the inStream. * * @param inStream the InputStream from which to load the image fraction * @param rect specifies the rectangular region to load as the image * @throws IOException if an error during loading occurs *//*from w w w . ja v a 2s . com*/ public void loadFragment(InputStream inStream, Rectangle rect) throws IOException { ImageInputStream imageStream = ImageIO.createImageInputStream(inStream); ImageReader reader = ImageIO.getImageReaders(imageStream).next(); ImageReadParam param = reader.getDefaultReadParam(); param.setSourceRegion(rect); reader.setInput(imageStream, true, true); this.image = reader.read(0, param); reader.dispose(); imageStream.close(); }
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 ww. jav a 2 s . c om 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.apache.xmlgraphics.image.loader.impl.imageio.ImageLoaderImageIO.java
/** {@inheritDoc} */ public Image loadImage(ImageInfo info, Map hints, ImageSessionContext session) throws ImageException, IOException { RenderedImage imageData = null; IIOException firstException = null; IIOMetadata iiometa = (IIOMetadata) info.getCustomObjects().get(ImageIOUtil.IMAGEIO_METADATA); boolean ignoreMetadata = (iiometa != null); boolean providerIgnoresICC = false; Source src = session.needSource(info.getOriginalURI()); ImageInputStream imgStream = ImageUtil.needImageInputStream(src); try {// w w w . j a v a 2 s . co m Iterator iter = ImageIO.getImageReaders(imgStream); while (iter.hasNext()) { ImageReader reader = (ImageReader) iter.next(); try { imgStream.mark(); ImageReadParam param = reader.getDefaultReadParam(); reader.setInput(imgStream, false, ignoreMetadata); final int pageIndex = ImageUtil.needPageIndexFromURI(info.getOriginalURI()); try { if (ImageFlavor.BUFFERED_IMAGE.equals(this.targetFlavor)) { imageData = reader.read(pageIndex, param); } else { imageData = reader.read(pageIndex, param); //imageData = reader.readAsRenderedImage(pageIndex, param); //TODO Reenable the above when proper listeners are implemented //to react to late pixel population (so the stream can be closed //properly). } if (iiometa == null) { iiometa = reader.getImageMetadata(pageIndex); } providerIgnoresICC = checkProviderIgnoresICC(reader.getOriginatingProvider()); break; //Quit early, we have the image } catch (IndexOutOfBoundsException indexe) { throw new ImageException("Page does not exist. Invalid image index: " + pageIndex); } catch (IllegalArgumentException iae) { //Some codecs like com.sun.imageio.plugins.wbmp.WBMPImageReader throw //IllegalArgumentExceptions when they have trouble parsing the image. throw new ImageException("Error loading image using ImageIO codec", iae); } catch (IIOException iioe) { if (firstException == null) { firstException = iioe; } else { log.debug("non-first error loading image: " + iioe.getMessage()); } } try { //Try fallback for CMYK images BufferedImage bi = getFallbackBufferedImage(reader, pageIndex, param); imageData = bi; firstException = null; //Clear exception after successful fallback attempt break; } catch (IIOException iioe) { //ignore } imgStream.reset(); } finally { reader.dispose(); } } } finally { ImageUtil.closeQuietly(src); //TODO Some codecs may do late reading. } if (firstException != null) { throw new ImageException("Error while loading image: " + firstException.getMessage(), firstException); } if (imageData == null) { throw new ImageException("No ImageIO ImageReader found ."); } ColorModel cm = imageData.getColorModel(); Color transparentColor = null; if (cm instanceof IndexColorModel) { //transparent color will be extracted later from the image } else { if (providerIgnoresICC && cm instanceof ComponentColorModel) { // Apply ICC Profile to Image by creating a new image with a new // color model. ICC_Profile iccProf = tryToExctractICCProfile(iiometa); if (iccProf != null) { ColorModel cm2 = new ComponentColorModel(new ICC_ColorSpace(iccProf), cm.hasAlpha(), cm.isAlphaPremultiplied(), cm.getTransparency(), cm.getTransferType()); WritableRaster wr = Raster.createWritableRaster(imageData.getSampleModel(), null); imageData.copyData(wr); BufferedImage bi = new BufferedImage(cm2, wr, cm2.isAlphaPremultiplied(), null); imageData = bi; cm = cm2; } } // ImageIOUtil.dumpMetadataToSystemOut(iiometa); // Retrieve the transparent color from the metadata if (iiometa != null && iiometa.isStandardMetadataFormatSupported()) { Element metanode = (Element) iiometa.getAsTree(IIOMetadataFormatImpl.standardMetadataFormatName); Element dim = ImageIOUtil.getChild(metanode, "Transparency"); if (dim != null) { Element child; child = ImageIOUtil.getChild(dim, "TransparentColor"); if (child != null) { String value = child.getAttribute("value"); if (value == null || value.length() == 0) { //ignore } else if (cm.getNumColorComponents() == 1) { int gray = Integer.parseInt(value); transparentColor = new Color(gray, gray, gray); } else { StringTokenizer st = new StringTokenizer(value); transparentColor = new Color(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken())); } } } } } if (ImageFlavor.BUFFERED_IMAGE.equals(this.targetFlavor)) { return new ImageBuffered(info, (BufferedImage) imageData, transparentColor); } else { return new ImageRendered(info, imageData, transparentColor); } }
From source file:org.medici.bia.controller.manuscriptviewer.IIPImageServerController.java
/** * This method retun a specific tiled image. * /*ww w .j av a 2 s. c o m*/ * @param httpServletRequest * @param httpServletResponse */ private void generateFullImage(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) { File imageFile = new File(ApplicationPropertyManager.getApplicationProperty("iipimage.image.path") + httpServletRequest.getParameter("FIF")); 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); ImageReader reader = readers.next(); reader.setInput(imageInputStream, true, true); // Reading image position requested Integer imageFullIndex = NumberUtils.createInteger(httpServletRequest.getParameter("full")); // Positioning at correct page BufferedImage pageImage = reader.read(imageFullIndex); // preparing image for output ImageIO.write(pageImage, "jpeg", byteArrayOutputStream); inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); // writing image to output httpServletResponse.setContentType("image/jpeg"); IOUtils.copy(inputStream, httpServletResponse.getOutputStream()); } // Flushing request httpServletResponse.getOutputStream().flush(); } catch (IOException ioException) { logger.debug(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) { } } }