List of usage examples for javax.imageio ImageWriter dispose
public void dispose()
From source file:org.getobjects.appserver.publisher.GoDefaultRenderer.java
/** * Renders a java.awt.BufferedImage to the WOResponse of the given context. * Remember to configure:<pre>/* w ww . j a v a 2 s.c om*/ * -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 GoInternalErrorException("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 GoInternalErrorException("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.getobjects.appserver.publisher.JoDefaultRenderer.java
/** * Renders a java.awt.BufferedImage to the WOResponse of the given context. * Remember to configure:<pre>//from 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.AbstractImageOperation.java
/** * Executes an image operation.// w ww . j a v a2 s . c o m * * @param data the image data. The stream is closed by this method. * @param mimeType MIME type of the image * * @throws GalleryException when the image operation fails */ public void execute(InputStream data, String mimeType) throws GalleryException { ImageReader reader = null; ImageWriter writer = null; try { reader = ImageUtils.getImageReader(mimeType); if (reader == null) { throw new GalleryException("Unsupported MIME type for reading: " + mimeType); } writer = ImageUtils.getImageWriter(mimeType); if (writer == null) { throw new GalleryException("Unsupported MIME type for writing: " + mimeType); } execute(data, reader, writer); } catch (IOException e) { throw new GalleryException("Could not execute image operation", e); } finally { // the != null checks are unnecessary, but otherwise Sonar will report critical issues if (reader != null) { reader.dispose(); } if (writer != null) { writer.dispose(); } IOUtils.closeQuietly(data); } }
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 w w w . jav a 2 s .c o m * @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/*w w w .j av a2 s. co m*/ * @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//from w ww . j a v a 2 s . 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 . j ava2s .c o m*/ @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);/* ww w . j a va2s . co m*/ writer.write(null, new IIOImage((RenderedImage) image, null, null), param); writer.dispose(); imageOut.close(); }
From source file:org.sejda.sambox.pdmodel.graphics.image.JPEGFactory.java
private static void encodeImageToJPEGStream(BufferedImage image, float quality, int dpi, OutputStream out) throws IOException { // encode to JPEG ImageOutputStream ios = null; ImageWriter imageWriter = null; try {//from w w w . j a v a2 s.c om // find JAI writer imageWriter = ImageIO.getImageWritersBySuffix("jpeg").next(); ios = ImageIO.createImageOutputStream(out); imageWriter.setOutput(ios); // add compression JPEGImageWriteParam jpegParam = (JPEGImageWriteParam) imageWriter.getDefaultWriteParam(); jpegParam.setCompressionMode(JPEGImageWriteParam.MODE_EXPLICIT); jpegParam.setCompressionQuality(quality); // add metadata ImageTypeSpecifier imageTypeSpecifier = new ImageTypeSpecifier(image); IIOMetadata data = imageWriter.getDefaultImageMetadata(imageTypeSpecifier, jpegParam); Element tree = (Element) data.getAsTree("javax_imageio_jpeg_image_1.0"); Element jfif = (Element) tree.getElementsByTagName("app0JFIF").item(0); jfif.setAttribute("Xdensity", Integer.toString(dpi)); jfif.setAttribute("Ydensity", Integer.toString(dpi)); jfif.setAttribute("resUnits", "1"); // 1 = dots/inch // write imageWriter.write(data, new IIOImage(image, null, null), jpegParam); } finally { // clean up IOUtils.closeQuietly(out); if (ios != null) { ios.close(); } if (imageWriter != null) { imageWriter.dispose(); } } }
From source file:org.tinymediamanager.core.ImageCache.java
/** * Scale image to fit in the given width. * /*from w w w. j a v a 2 s . c o m*/ * @param imageUrl * the image url * @param width * the width * @return the input stream * @throws IOException * Signals that an I/O exception has occurred. * @throws InterruptedException */ public static InputStream scaleImage(String imageUrl, int width) throws IOException, InterruptedException { Url url = new Url(imageUrl); BufferedImage originalImage = null; try { originalImage = createImage(url.getBytes()); } catch (Exception e) { throw new IOException(e.getMessage()); } Point size = new Point(); size.x = width; size.y = size.x * originalImage.getHeight() / originalImage.getWidth(); // BufferedImage scaledImage = Scaling.scale(originalImage, size.x, size.y); BufferedImage scaledImage = Scalr.resize(originalImage, Scalr.Method.QUALITY, Scalr.Mode.AUTOMATIC, size.x, size.y, Scalr.OP_ANTIALIAS); originalImage = null; ImageWriter imgWrtr = null; ImageWriteParam imgWrtrPrm = null; // here we have two different ways to create our thumb // a) a scaled down jpg/png (without transparency) which we have to modify since OpenJDK cannot call native jpg encoders // b) a scaled down png (with transparency) which we can store without any more modifying as png if (hasTransparentPixels(scaledImage)) { // transparent image -> png imgWrtr = ImageIO.getImageWritersByFormatName("png").next(); imgWrtrPrm = imgWrtr.getDefaultWriteParam(); } else { // non transparent image -> jpg // convert to rgb BufferedImage rgb = new BufferedImage(scaledImage.getWidth(), scaledImage.getHeight(), BufferedImage.TYPE_INT_RGB); ColorConvertOp xformOp = new ColorConvertOp(null); xformOp.filter(scaledImage, rgb); imgWrtr = ImageIO.getImageWritersByFormatName("jpg").next(); imgWrtrPrm = imgWrtr.getDefaultWriteParam(); imgWrtrPrm.setCompressionMode(JPEGImageWriteParam.MODE_EXPLICIT); imgWrtrPrm.setCompressionQuality(0.80f); scaledImage = rgb; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageOutputStream output = ImageIO.createImageOutputStream(baos); imgWrtr.setOutput(output); IIOImage outputImage = new IIOImage(scaledImage, null, null); imgWrtr.write(null, outputImage, imgWrtrPrm); imgWrtr.dispose(); scaledImage = null; byte[] bytes = baos.toByteArray(); output.flush(); output.close(); baos.close(); return new ByteArrayInputStream(bytes); }