List of usage examples for javax.imageio ImageReader read
public abstract BufferedImage read(int imageIndex, ImageReadParam param) throws IOException;
From source file:jails.http.converter.BufferedImageHttpMessageConverter.java
public BufferedImage read(Class<? extends BufferedImage> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { ImageInputStream imageInputStream = null; ImageReader imageReader = null; try {//from ww w . ja v a 2 s . co m imageInputStream = createImageInputStream(inputMessage.getBody()); MediaType contentType = inputMessage.getHeaders().getContentType(); Iterator<ImageReader> imageReaders = ImageIO.getImageReadersByMIMEType(contentType.toString()); if (imageReaders.hasNext()) { imageReader = imageReaders.next(); ImageReadParam irp = imageReader.getDefaultReadParam(); process(irp); imageReader.setInput(imageInputStream, true); return imageReader.read(0, irp); } else { throw new HttpMessageNotReadableException( "Could not find javax.imageio.ImageReader for Content-Type [" + contentType + "]"); } } finally { if (imageReader != null) { imageReader.dispose(); } if (imageInputStream != null) { try { imageInputStream.close(); } catch (IOException ex) { // ignore } } } }
From source file:org.psystems.dicomweb.Dcm2Jpg.java
public void convert(File src, File dest) throws IOException { Iterator<ImageReader> iter = ImageIO.getImageReadersByFormatName("DICOM"); ImageReader reader = iter.next(); DicomImageReadParam param = (DicomImageReadParam) reader.getDefaultReadParam(); param.setWindowCenter(center);//from w ww . j a v a2 s .c o m param.setWindowWidth(width); param.setVoiLutFunction(vlutFct); param.setPresentationState(prState); param.setPValue2Gray(pval2gray); param.setAutoWindowing(autoWindowing); ImageInputStream iis = ImageIO.createImageInputStream(src); BufferedImage bi; OutputStream out = null; try { reader.setInput(iis, false); bi = reader.read(frame - 1, param); if (bi == null) { System.out.println("\nError: " + src + " - couldn't read!"); return; } out = new BufferedOutputStream(new FileOutputStream(dest)); JPEGImageEncoder enc = JPEGCodec.createJPEGEncoder(out); enc.encode(bi); } finally { CloseUtils.safeClose(iis); CloseUtils.safeClose(out); } System.out.print('.'); }
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 ava 2s .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: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. java 2s . 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.dcm4che2.tool.dcm2jpg.Dcm2Jpg.java
public void convert(File src, File dest) throws IOException { Iterator<ImageReader> iter = ImageIO.getImageReadersByFormatName("DICOM"); ImageReader reader = iter.next(); DicomImageReadParam param = (DicomImageReadParam) reader.getDefaultReadParam(); param.setWindowCenter(center);//from w w w . j a va2 s.c o m param.setWindowWidth(width); param.setVoiLutFunction(vlutFct); param.setPresentationState(prState); param.setPValue2Gray(pval2gray); param.setAutoWindowing(autoWindowing); ImageInputStream iis = ImageIO.createImageInputStream(src); BufferedImage bi; try { reader.setInput(iis, false); bi = reader.read(frame - 1, param); if (bi == null) { System.out.println("\nError: " + src + " - couldn't read!"); return; } if (imageWriterClassname == null) { encodeByJPEGEncoder(bi, dest); } else { encodeByImageIO(bi, dest); } } finally { CloseUtils.safeClose(iis); } System.out.print('.'); }
From source file:nitf.imageio.NITFReader.java
/** * Reads image data as bytes for the given region, and writes it to the * given writable raster/* www . j av a 2 s. c om*/ * * @param sourceRegion * @param sourceXSubsampling * @param sourceYSubsampling * @param bandOffsets * @param destinationOffset * @param imRas * @return Raster * @throws IOException */ protected void readRaster(int imageIndex, Rectangle sourceRegion, Rectangle destRegion, int sourceXSubsampling, int sourceYSubsampling, int[] bandOffsets, int pixelSize, Point destinationOffset, WritableRaster imRas) throws IOException { checkIndex(imageIndex); try { ImageSubheader subheader = record.getImages()[imageIndex].getSubheader(); int numCols = subheader.getNumCols().getIntData(); int numRows = subheader.getNumRows().getIntData(); // try to optimize the read call by reading in the entire // image at once if ((destRegion.height * sourceYSubsampling) == numRows && (destRegion.width * sourceXSubsampling) == numCols) { readFullImage(imageIndex, destRegion, sourceXSubsampling, sourceYSubsampling, bandOffsets, pixelSize, imRas); return; } // the general purpose case else { int colBytes = destRegion.width * pixelSize; int dstMinX = imRas.getMinX(); int dstMaxX = dstMinX + imRas.getWidth() - 1; int dstMinY = imRas.getMinY(); int dstMaxY = dstMinY + imRas.getHeight() - 1; // int swap = 0; int nBands = subheader.getBandCount(); /* * NOTE: This is a "fix" that will be removed once the * underlying NITRO library gets patched. Currently, if you make * a request of a single band, it doesn't matter which band you * request - the data from the first band will be returned * regardless. This is obviously wrong. To thwart this, we will * read all bands, then scale down what we return to the user * based on their actual request. */ int[] requestBands = new int[nBands]; for (int i = 0; i < nBands; ++i) requestBands[i] = i; byte[][] rowBuf = new byte[requestBands.length][colBytes]; // make a SubWindow from the params // TODO may want to read by blocks or rows to make faster and // more // memory efficient SubWindow window; window = new SubWindow(); window.setNumBands(requestBands.length); window.setBandList(requestBands); window.setNumCols(destRegion.width); window.setNumRows(1); window.setStartCol(sourceRegion.x); window.setStartRow(sourceRegion.y); // the NITRO library can do the subsampling for us if (sourceYSubsampling != 1 || sourceXSubsampling != 1) { DownSampler downSampler = new PixelSkipDownSampler(sourceYSubsampling, sourceXSubsampling); window.setDownSampler(downSampler); } // String pixelJustification = record.getImages()[imageIndex] // .getSubheader().getPixelJustification().getStringData() // .trim(); // swap = pixelJustification.equals("R") ? 1 : 0; List<ByteBuffer> bandBufs = new ArrayList<ByteBuffer>(); for (int i = 0; i < requestBands.length; ++i) { ByteBuffer bandBuf = null; bandBuf = ByteBuffer.wrap(rowBuf[i]); // bandBuf.order(ByteOrder.nativeOrder()); // bandBuf.order(swap == 0 ? ByteOrder.BIG_ENDIAN // : ByteOrder.LITTLE_ENDIAN); bandBufs.add(bandBuf); } nitf.ImageReader imageReader = getImageReader(imageIndex); for (int srcY = 0; srcY < sourceRegion.height; srcY++) { if (sourceYSubsampling != 1 && (srcY % sourceYSubsampling) != 0) continue; window.setStartRow(sourceRegion.y + srcY); // Read the row try { imageReader.read(window, rowBuf); } catch (NITFException e) { throw new IIOException("Error reading line " + srcY, e); } // Determine where the row will go in the destination int dstY = destinationOffset.y + srcY / sourceYSubsampling; if (dstY < dstMinY) { continue; // The row is above imRas } if (dstY > dstMaxY) { break; // We're done with the image } // Copy each (subsampled) source pixel into imRas for (int srcX = 0, dstX = destinationOffset.x; srcX < colBytes; srcX += pixelSize, dstX++) { if (dstX < dstMinX) { continue; } if (dstX > dstMaxX) { break; } for (int i = 0; i < bandOffsets.length; ++i) { ByteBuffer bandBuf = bandBufs.get(bandOffsets[i]); switch (pixelSize) { case 1: imRas.setSample(dstX, dstY, i, bandBuf.get(srcX)); break; case 2: imRas.setSample(dstX, dstY, i, bandBuf.getShort(srcX)); break; case 4: imRas.setSample(dstX, dstY, i, bandBuf.getFloat(srcX)); break; case 8: imRas.setSample(dstX, dstY, i, bandBuf.getDouble(srcX)); break; } } } } } } catch (NITFException e1) { throw new IOException(ExceptionUtils.getStackTrace(e1)); } }
From source file:org.psystems.dicom.daemon.Dcm2Jpg.java
public void convert(File src, File dest) throws IOException { Iterator<ImageReader> iter = ImageIO.getImageReadersByFormatName("DICOM"); ImageReader reader = iter.next(); DicomImageReadParam param = (DicomImageReadParam) reader.getDefaultReadParam(); param.setWindowCenter(center);//from w w w . j a v a 2 s . c o m param.setWindowWidth(width); param.setVoiLutFunction(vlutFct); param.setPresentationState(prState); param.setPValue2Gray(pval2gray); param.setAutoWindowing(autoWindowing); ImageInputStream iis = ImageIO.createImageInputStream(src); BufferedImage bi; OutputStream out = null; try { reader.setInput(iis, false); if (reader.getNumImages(false) <= 0) { System.out.println("\nError: " + src + " - Don't haven any images!"); return; } // System.out.println("!!! frame="+frame+" p="+reader.getNumImages(false)); bi = reader.read(frame - 1, param); if (bi == null) { System.out.println("\nError: " + src + " - couldn't read!"); return; } out = new BufferedOutputStream(new FileOutputStream(dest)); JPEGImageEncoder enc = JPEGCodec.createJPEGEncoder(out); enc.encode(bi); } finally { CloseUtils.safeClose(iis); CloseUtils.safeClose(out); } System.out.print('.'); }
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 av a 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:com.funambol.foundation.util.MediaUtils.java
/** * Creates the thumbnail./*from ww w . j a v a 2s . c o m*/ * * @param imageFile the image file * @param thumbFile the empty thumbnail file * @param thumbX the width of the thumbnail * @param thumbY the height of the thumbnail * @param imageName the image file name with extension * @param tolerance the percentage of tolerance before creating a thumbnail * @return true is the thumbnail has been created, false otherwise * @throws IOException if an error occurs */ private static boolean createThumbnail(File imageFile, File thumbFile, int thumbX, int thumbY, String imageName, double tolerance) throws IOException { FileInputStream fileis = null; ImageInputStream imageis = null; Iterator readers = null; try { readers = ImageIO.getImageReadersByFormatName(imageName.substring(imageName.lastIndexOf('.') + 1)); if (readers == null || (!readers.hasNext())) { throw new IOException("File not supported"); } ImageReader reader = (ImageReader) readers.next(); fileis = new FileInputStream(imageFile); imageis = ImageIO.createImageInputStream(fileis); reader.setInput(imageis, true); // Determines thumbnail height, width and quality int thumbWidth = thumbX; int thumbHeight = thumbY; double thumbRatio = (double) thumbWidth / (double) thumbHeight; int imageWidth = reader.getWidth(0); int imageHeight = reader.getHeight(0); // // Don't create the thumbnail if the original file is smaller // than required size increased by % tolerance // if (imageWidth <= (thumbWidth * (1 + tolerance / 100)) && imageHeight <= (thumbHeight * (1 + tolerance / 100))) { return false; } double imageRatio = (double) imageWidth / (double) imageHeight; if (thumbRatio < imageRatio) { thumbHeight = (int) (thumbWidth / imageRatio); } else { thumbWidth = (int) (thumbHeight * imageRatio); } ImageReadParam param = reader.getDefaultReadParam(); param.setSourceSubsampling(3, 3, 0, 0); BufferedImage bi = reader.read(0, param); Image thumb = bi.getScaledInstance(thumbWidth, thumbHeight, Image.SCALE_SMOOTH); BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB); Graphics2D graphics2D = thumbImage.createGraphics(); graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); graphics2D.drawImage(thumb, 0, 0, thumbWidth, thumbHeight, null); FileOutputStream fileOutputStream = new FileOutputStream(thumbFile); ImageIO.write(thumbImage, "jpg", fileOutputStream); thumb.flush(); thumbImage.flush(); fileOutputStream.flush(); fileOutputStream.close(); graphics2D.dispose(); } finally { if (fileis != null) { fileis.close(); } if (imageis != null) { imageis.close(); } } return true; }
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 ww. j av a2s. c om * @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; }