List of usage examples for javax.imageio IIOImage IIOImage
public IIOImage(Raster raster, List<? extends BufferedImage> thumbnails, IIOMetadata metadata)
From source file:org.getobjects.appserver.publisher.JoDefaultRenderer.java
/** * Renders a java.awt.BufferedImage to the WOResponse of the given context. * Remember to configure:<pre>/*w w w. ja va2 s . c o m*/ * -Djava.awt.headless=true</pre> * (thats the VM arguments of the run panel in Eclipse) * * @param _img - the BufferedImage object to render * @param _ctx - the WOContext to render the image in * @return null if everything went fine, an Exception otherwise */ public Exception renderBufferedImage(BufferedImage _img, WOContext _ctx) { // TBD: this method could be improved a lot, but it works well enough for // simple cases if (_img == null) return new JoInternalErrorException("got no image to render"); /* find a proper image writer */ String usedType = null; Iterator<ImageWriter> writers; ImageWriter writer = null; WORequest rq = _ctx.request(); if (rq != null) { // TBD: just iterate over the accepted (image/) types (considering // the value quality) and check each if (rq.acceptsContentType("image/png", false /* direct match */)) { if ((writers = ImageIO.getImageWritersByMIMEType("image/png")) != null) writer = writers.next(); if (writer != null) usedType = "image/png"; } if (writer == null && rq.acceptsContentType("image/gif", false)) { if ((writers = ImageIO.getImageWritersByMIMEType("image/gif")) != null) writer = writers.next(); if (writer != null) usedType = "image/gif"; } if (writer == null && rq.acceptsContentType("image/jpeg", false)) { if ((writers = ImageIO.getImageWritersByMIMEType("image/jpeg")) != null) writer = writers.next(); if (writer != null) usedType = "image/jpeg"; } } if (writer == null) { if ((writers = ImageIO.getImageWritersByMIMEType("image/png")) != null) writer = writers.next(); if (writer != null) usedType = "image/png"; } if (writer == null) return new JoInternalErrorException("found no writer for image: " + _img); /* prepare WOResponse */ WOResponse r = _ctx.response(); r.setStatus(WOMessage.HTTP_STATUS_OK); r.setHeaderForKey("inline", "content-disposition"); if (usedType != null) r.setHeaderForKey(usedType, "content-type"); // TBD: do we know the content-length? If not, should we generate to a // buffer to avoid confusing the browser (IE ...) r.enableStreaming(); /* write */ ImageOutputStream ios = null; try { ios = ImageIO.createImageOutputStream(rq.outputStream()); } catch (IOException e) { log.warn("could not create image output stream: " + _img); return e; } writer.setOutput(ios); try { writer.write(null, new IIOImage(_img, null, null), null); ios.flush(); writer.dispose(); ios.close(); } catch (IOException e) { log.warn("failed to write image to stream", e); return e; } return null; /* everything is awesome O */ }
From source file:org.hippoecm.frontend.plugins.gallery.imageutil.ImageUtils.java
/** * Returns the data of a {@link BufferedImage} as a binary output stream. If the image is <code>null</code>, * a stream of zero bytes is returned./*from w w w .j a v a 2s. c om*/ * * @param writer the writer to use for writing the image data. * @param image the image to write. * @param compressionQuality a float between 0 and 1 that indicates the desired compression quality. Values lower than * 0 will be interpreted as 0, values higher than 1 will be interpreted as 1. * * @return an output stream with the data of the given image. * * @throws IOException when creating the binary output stream failed. */ public static ByteArrayOutputStream writeImage(ImageWriter writer, BufferedImage image, float compressionQuality) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); if (image != null) { ImageOutputStream ios = null; try { ios = ImageIO.createImageOutputStream(out); writer.setOutput(ios); // write compressed images with high quality final ImageWriteParam writeParam = writer.getDefaultWriteParam(); if (writeParam.canWriteCompressed()) { String[] compressionTypes = writeParam.getCompressionTypes(); if (compressionTypes != null && compressionTypes.length > 0) { writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); writeParam.setCompressionType(compressionTypes[0]); // ensure a compression quality between 0 and 1 float trimmedCompressionQuality = Math.max(compressionQuality, 0); trimmedCompressionQuality = Math.min(trimmedCompressionQuality, 1f); writeParam.setCompressionQuality(trimmedCompressionQuality); } } final IIOImage iioImage = new IIOImage(image, null, null); writer.write(null, iioImage, writeParam); ios.flush(); } finally { if (ios != null) { ios.close(); } } } return out; }
From source file:org.mycore.iview2.frontend.MCRTileCombineServlet.java
/** * Transmits combined file or sends thumbnail. * Uses {@link HttpServletRequest#getAttribute(String)} to retrieve information generated by {@link #think(MCRServletJob)}. * <table>/*from w w w . j a v a 2s. c o m*/ * <caption>description of {@link HttpServletRequest} attributes</caption> * <tr><th>keyName</th><th>type</th><th>description</th></tr> * <tr><td>{@link #THUMBNAIL_KEY}</td><td>{@link File}</td><td>.iview2 File with all tiles in it</td></tr> * <tr><td>{@link #IMAGE_KEY}</td><td>{@link BufferedImage}</td> * <td>generated image if <code>zoomLevel != 0</code> and no implementation of {@link MCRFooterInterface} defined</td></tr> * </table> */ @Override protected void render(final MCRServletJob job, final Exception ex) throws Exception { if (job.getResponse().isCommitted()) { return; } if (ex != null) { throw ex; } //check for thumnail final File iviewFile = ((Path) job.getRequest().getAttribute(THUMBNAIL_KEY)).toFile(); final BufferedImage combinedImage = (BufferedImage) job.getRequest().getAttribute(IMAGE_KEY); if (iviewFile != null && combinedImage == null) { sendThumbnail(iviewFile, job.getResponse()); return; } //send combined image job.getResponse().setHeader("Cache-Control", "max-age=" + MCRTileServlet.MAX_AGE); job.getResponse().setContentType("image/jpeg"); job.getResponse().setDateHeader("Last-Modified", iviewFile.lastModified()); final Date expires = new Date(System.currentTimeMillis() + MCRTileServlet.MAX_AGE * 1000); LOGGER.info("Last-Modified: " + new Date(iviewFile.lastModified()) + ", expire on: " + expires); job.getResponse().setDateHeader("Expires", expires.getTime()); final ImageWriter curImgWriter = imageWriter.get(); try (ServletOutputStream sout = job.getResponse().getOutputStream(); ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(sout);) { curImgWriter.setOutput(imageOutputStream); final IIOImage iioImage = new IIOImage(combinedImage, null, null); curImgWriter.write(null, iioImage, imageWriteParam); } finally { curImgWriter.reset(); } }
From source file:org.olat.core.commons.services.image.spi.ImageHelperImpl.java
/** * Can change this to choose a better compression level as the default * @param image/*from ww w.java2 s.c om*/ * @param scaledImage * @return */ public static boolean writeTo(BufferedImage image, File scaledImage, Size scaledSize, String outputFormat) { try { if (!StringHelper.containsNonWhitespace(outputFormat)) { outputFormat = OUTPUT_FORMAT; } Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(outputFormat); if (writers.hasNext()) { ImageWriter writer = writers.next(); ImageWriteParam iwp = getOptimizedImageWriteParam(writer, scaledSize); IIOImage iiOImage = new IIOImage(image, null, null); ImageOutputStream iOut = new FileImageOutputStream(scaledImage); writer.setOutput(iOut); writer.write(null, iiOImage, iwp); writer.dispose(); iOut.flush(); iOut.close(); return true; } else { return ImageIO.write(image, outputFormat, scaledImage); } } catch (IOException e) { return false; } }
From source file:org.olat.core.commons.services.image.spi.ImageHelperImpl.java
/** * Can change this to choose a better compression level as the default * @param image//from ww w. j a va2s .c om * @param scaledImage * @return */ private static boolean writeTo(BufferedImage image, OutputStream scaledImage, Size scaledSize, String outputFormat) { try { if (!StringHelper.containsNonWhitespace(outputFormat)) { outputFormat = OUTPUT_FORMAT; } Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(outputFormat); if (writers.hasNext()) { ImageWriter writer = writers.next(); ImageWriteParam iwp = getOptimizedImageWriteParam(writer, scaledSize); IIOImage iiOImage = new IIOImage(image, null, null); ImageOutputStream iOut = new MemoryCacheImageOutputStream(scaledImage); writer.setOutput(iOut); writer.write(null, iiOImage, iwp); writer.dispose(); iOut.flush(); iOut.close(); return true; } else { return ImageIO.write(image, outputFormat, scaledImage); } } catch (IOException e) { return false; } }
From source file:org.onehippo.forge.gallerymagick.core.command.ScalrProcessorUtils.java
/** * Resize the given image {@code sourceFile} with resizing it to {@code width} and {@code height} * and store the resized image to {@code targetFile}, with appending {@code extraOptions} in the command line if provided. * @param sourceFile source image file/* w w w. j av a 2s .c o m*/ * @param targetFile target image file * @param dimension image dimension * @param extraOptions extra command line options * @throws IOException if IO exception occurs */ public static void resizeImage(File sourceFile, File targetFile, ImageDimension dimension, String... extraOptions) throws IOException { if (dimension == null) { throw new IllegalArgumentException("Invalid dimension: " + dimension); } ImageReader reader = null; ImageWriter writer = null; try { reader = getImageReader(sourceFile); if (reader == null) { throw new IllegalArgumentException( "Unsupported image file name extension for reading: " + sourceFile); } writer = getImageWriter(targetFile); if (writer == null) { throw new IllegalArgumentException( "Unsupported image file name extension for writing: " + targetFile); } BufferedImage sourceImage = reader.read(0); BufferedImage resizedImage = Scalr.resize(sourceImage, Scalr.Method.QUALITY, Scalr.Mode.AUTOMATIC, dimension.getWidth(), dimension.getHeight()); final ImageWriteParam writeParam = writer.getDefaultWriteParam(); if (writeParam.canWriteCompressed()) { String[] compressionTypes = writeParam.getCompressionTypes(); if (compressionTypes != null && compressionTypes.length > 0) { writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); writeParam.setCompressionType(compressionTypes[0]); writeParam.setCompressionQuality(1.0f); } } final IIOImage iioImage = new IIOImage(resizedImage, null, null); writer.write(null, iioImage, writeParam); } finally { if (reader != null) { reader.dispose(); } if (writer != null) { writer.dispose(); } } }
From source file:org.photovault.imginfo.CreateCopyImageCommand.java
/** Helper function to save a rendered image to file @param instanceFile The file into which the image will be saved @param img Image that willb e saved//from w w w . ja v a 2s .c om @param xmpData XPM metadata packet that should be saved with the image @throws PhotovaultException if saving does not succeed */ protected void saveImage(File instanceFile, RenderedImage img, byte[] xmpData) throws PhotovaultException { ImageOutputStream out = null; log.debug("Entry: saveImage, file = " + instanceFile.getAbsolutePath()); try { out = new FileImageOutputStream(instanceFile); } catch (IOException e) { log.error("Error writing image: " + e.getMessage()); throw new PhotovaultException(e.getMessage()); } if (img.getSampleModel().getSampleSize(0) == 16) { log.debug("16 bit image, converting to 8 bits"); double[] subtract = new double[1]; subtract[0] = 0; double[] divide = new double[1]; divide[0] = 1. / 256.; // Now we can rescale the pixels gray levels: ParameterBlock pbRescale = new ParameterBlock(); pbRescale.add(divide); pbRescale.add(subtract); pbRescale.addSource(img); PlanarImage outputImage = (PlanarImage) JAI.create("rescale", pbRescale, null); // Make sure it is a byte image - force conversion. ParameterBlock pbConvert = new ParameterBlock(); pbConvert.addSource(outputImage); pbConvert.add(DataBuffer.TYPE_BYTE); img = JAI.create("format", pbConvert); } IIOImage iioimg = new IIOImage(img, null, null); /* Not all encoders support metadata handling */ Iterator writers = ImageIO.getImageWritersByFormatName("jpeg"); ImageWriter imgwriter = null; while (writers.hasNext()) { imgwriter = (ImageWriter) writers.next(); if (imgwriter.getClass().getName().endsWith("JPEGImageEncoder")) { // Break on finding the core provider. break; } } if (imgwriter == null) { System.err.println("Cannot find core JPEG writer!"); } imgwriter.addIIOWriteWarningListener(new IIOWriteWarningListener() { public void warningOccurred(ImageWriter arg0, int arg1, String arg2) { log.warn("Warning from ImageWriter: " + arg2); } }); ImageWriteParam params = imgwriter.getDefaultWriteParam(); ImageTypeSpecifier its = ImageTypeSpecifier.createFromRenderedImage(img); IIOMetadata metadata = imgwriter.getDefaultImageMetadata(its, null); IIOMetadataNode metatop = (IIOMetadataNode) metadata.getAsTree("javax_imageio_jpeg_image_1.0"); NodeList markerSeqNodes = metatop.getElementsByTagName("markerSequence"); if (markerSeqNodes.getLength() > 0) { IIOMetadataNode xmpNode = new IIOMetadataNode("unknown"); xmpNode.setAttribute("MarkerTag", "225"); xmpNode.setUserObject(xmpData); markerSeqNodes.item(0).appendChild(xmpNode); } try { metadata.setFromTree("javax_imageio_jpeg_image_1.0", metatop); } catch (Exception e) { log.warn("error editing metadata: " + e.getMessage()); e.printStackTrace(); throw new PhotovaultException("error setting image metadata: \n" + e.getMessage()); } iioimg.setMetadata(metadata); try { imgwriter.setOutput(out); imgwriter.write(iioimg); } catch (IOException e) { log.warn("Exception while encoding" + e.getMessage()); throw new PhotovaultException( "Error writing instance " + instanceFile.getAbsolutePath() + ": " + e.getMessage()); } finally { try { out.close(); } catch (IOException e) { log.warn("Exception while closing file: " + e.getMessage()); imgwriter.dispose(); throw new PhotovaultException( "Error writing instance " + instanceFile.getAbsolutePath() + ": " + e.getMessage()); } imgwriter.dispose(); } log.debug("Exit: saveImage"); }
From source file:org.polymap.core.data.image.ImageEncodeProcessor.java
private void imageioEncodeJPEG(Image image, ChunkedResponseOutputStream out) throws IOException { // this code is from http://forums.sun.com/thread.jspa?threadID=5197061 ImageWriter writer = ImageIO.getImageWritersByFormatName("jpeg").next(); ImageWriteParam param = writer.getDefaultWriteParam(); param.setSourceBands(new int[] { 0, 1, 2 }); ColorModel cm = new DirectColorModel(24, 0x00ff0000, // Red 0x0000ff00, // Green 0x000000ff, // Blue 0x0); // Alpha param.setDestinationType(new ImageTypeSpecifier(cm, cm.createCompatibleSampleModel(1, 1))); ImageOutputStream imageOut = ImageIO.createImageOutputStream(out); writer.setOutput(imageOut);// www.j a v a 2 s .c o m writer.write(null, new IIOImage((RenderedImage) image, null, null), param); writer.dispose(); imageOut.close(); }
From source file:org.psystems.dicomweb.Dcm2Dcm.java
/** * Recodes the images from the source transfer syntax, as read from the src * file, to the specified destination syntax. *//*from w ww .j av a2 s . co m*/ public void recodeImages(File src, File dest) throws IOException { ImageReader reader = new DicomImageReaderSpi().createReaderInstance(); ImageWriter writer = new DicomImageWriterSpi().createWriterInstance(); FileImageInputStream input = new FileImageInputStream(src); reader.setInput(input); if (dest.exists()) dest.delete(); FileImageOutputStream output = new FileImageOutputStream(dest); writer.setOutput(output); DicomStreamMetaData streamMeta = (DicomStreamMetaData) reader.getStreamMetadata(); DicomObject ds = streamMeta.getDicomObject(); DicomStreamMetaData writeMeta = (DicomStreamMetaData) writer.getDefaultStreamMetadata(null); DicomObject newDs = new BasicDicomObject(); ds.copyTo(newDs); writeMeta.setDicomObject(newDs); int frames = ds.getInt(Tag.NumberOfFrames, 1); LookupTable lut = prepareBitStrip(writeMeta, reader); newDs.putString(Tag.TransferSyntaxUID, VR.UI, destinationSyntax.uid()); if (overwriteObject != null) { overwriteObject.copyTo(newDs); } writer.prepareWriteSequence(writeMeta); for (int i = 0; i < frames; i++) { WritableRaster r = (WritableRaster) reader.readRaster(i, null); ColorModel cm = ColorModelFactory.createColorModel(ds); BufferedImage bi = new BufferedImage(cm, r, false, null); if (lut != null) { lut.lookup(bi.getRaster(), bi.getRaster()); } IIOImage iioimage = new IIOImage(bi, null, null); writer.writeToSequence(iioimage, null); } writer.endWriteSequence(); output.close(); input.close(); }
From source file:org.psystems.dicomweb.Dcm2DcmCopy.java
/** * Recodes the images from the source transfer syntax, as read from the src * file, to the specified destination syntax. *//*from ww w . ja va 2s.c om*/ public void recodeImages(File src, File dest) throws IOException { ImageReader reader = new DicomImageReaderSpi().createReaderInstance(); ImageWriter writer = new DicomImageWriterSpi().createWriterInstance(); FileImageInputStream input = new FileImageInputStream(src); reader.setInput(input); if (dest.exists()) dest.delete(); FileImageOutputStream output = new FileImageOutputStream(dest); writer.setOutput(output); DicomStreamMetaData streamMeta = (DicomStreamMetaData) reader.getStreamMetadata(); DicomObject ds = streamMeta.getDicomObject(); DicomStreamMetaData writeMeta = (DicomStreamMetaData) writer.getDefaultStreamMetadata(null); DicomObject newDs = new BasicDicomObject(); ds.copyTo(newDs); writeMeta.setDicomObject(newDs); int frames = ds.getInt(Tag.NumberOfFrames, 1); LookupTable lut = prepareBitStrip(writeMeta, reader); newDs.putString(Tag.TransferSyntaxUID, VR.UI, destinationSyntax.uid()); if (overwriteObject != null) { overwriteObject.copyTo(newDs); } writer.prepareWriteSequence(writeMeta); for (int i = 0; i < frames; i++) { WritableRaster r = (WritableRaster) reader.readRaster(i, null); ColorModel cm = ColorModelFactory.createColorModel(ds); BufferedImage bi = new BufferedImage(cm, r, false, null); if (lut != null) { lut.lookup(bi.getRaster(), bi.getRaster()); } IIOImage iioimage = new IIOImage(bi, null, null); writer.writeToSequence(iioimage, null); } writer.endWriteSequence(); output.close(); input.close(); }