List of usage examples for javax.imageio.stream ImageOutputStream flush
void flush() throws IOException;
From source file:lucee.runtime.img.Image.java
private void _writeOut(ImageOutputStream ios, String format, float quality, boolean noMeta) throws IOException, ExpressionException { if (quality < 0 || quality > 1) throw new IOException( "quality has an invalid value [" + quality + "], value has to be between 0 and 1"); if (StringUtil.isEmpty(format)) format = this.format; if (StringUtil.isEmpty(format)) throw new IOException("missing format"); BufferedImage im = image();//from w ww. j a v a2s. c o m //IIOMetadata meta = noMeta?null:metadata(format); IIOMetadata meta = noMeta ? null : getMetaData(null); ImageWriter writer = null; ImageTypeSpecifier type = ImageTypeSpecifier.createFromRenderedImage(im); Iterator<ImageWriter> iter = ImageIO.getImageWriters(type, format); if (iter.hasNext()) { writer = iter.next(); } if (writer == null) throw new IOException("no writer for format [" + format + "] available, available writer formats are [" + ListUtil.arrayToList(ImageUtil.getWriterFormatNames(), ",") + "]"); ImageWriteParam iwp = null; if ("jpg".equalsIgnoreCase(format)) { ColorModel cm = im.getColorModel(); if (cm.hasAlpha()) im = jpgImage(im); JPEGImageWriteParam jiwp = new JPEGImageWriteParam(Locale.getDefault()); jiwp.setOptimizeHuffmanTables(true); iwp = jiwp; } else iwp = writer.getDefaultWriteParam(); setCompressionModeEL(iwp, ImageWriteParam.MODE_EXPLICIT); setCompressionQualityEL(iwp, quality); writer.setOutput(ios); try { writer.write(meta, new IIOImage(im, null, meta), iwp); } finally { writer.dispose(); ios.flush(); } }
From source file:nl.b3p.imagetool.ImageTool.java
/** * Writes a JPEG, GIF or PNG image to the outputstream. * * @param bufferedImage BufferedImage created from the given images. * @param dw DataWrapper object in which the request object is stored. * @param extension String with the extension of the file * * @throws Exception/*from www . jav a 2s.co m*/ */ // <editor-fold defaultstate="" desc="writeOtherImage(BufferedImage bufferedImage, DataWrapper dw, String extension) method."> private static void writeOtherImage(BufferedImage bufferedImage, OutputStream os, String extension) throws Exception { //log.info("Writing JPG, GIF or PNG using ImageIO.write"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageOutputStream ios = ImageIO.createImageOutputStream(baos); ImageIO.write(bufferedImage, extension, ios); os.write(baos.toByteArray()); ios.flush(); ios.close(); }
From source file:nl.b3p.kaartenbalie.service.KBImageTool.java
/** Writes a JPEG, GIF or PNG image to the outputstream. * * @param bufferedImage BufferedImage created from the given images. * @param dw DataWrapper object in which the request object is stored. * @param extension String with the extension of the file * * @throws Exception/* w w w . ja v a2s . c o m*/ */ // <editor-fold defaultstate="" desc="writeOtherImage(BufferedImage bufferedImage, DataWrapper dw, String extension) method."> private static void writeOtherImage(BufferedImage bufferedImage, DataWrapper dw, String extension) throws Exception { //log.info("Writing JPG, GIF or PNG using ImageIO.write"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageOutputStream ios = ImageIO.createImageOutputStream(baos); ImageIO.write(bufferedImage, extension, ios); dw.write(baos); ios.flush(); ios.close(); }
From source file:org.apache.axis2.jaxws.marshaller.impl.alt.Attachment.java
private static byte[] createBytesFromImage(Image image, String mimeType) { try {/* w w w. j a va2 s. c o m*/ ImageWriter imageWriter = null; BufferedImage bufferedImage = (BufferedImage) image; ByteArrayOutputStream baos = new ByteArrayOutputStream(); Iterator iterator = javax.imageio.ImageIO.getImageWritersByMIMEType(mimeType); if (iterator.hasNext()) { imageWriter = (ImageWriter) iterator.next(); } ImageOutputStream ios = javax.imageio.ImageIO.createImageOutputStream(baos); imageWriter.setOutput(ios); imageWriter.write(new IIOImage(bufferedImage, null, null)); ios.flush(); imageWriter.dispose(); return baos.toByteArray(); } catch (IOException e) { throw ExceptionFactory.makeWebServiceException(e); } }
From source file:org.bigbluebuttonproject.fileupload.document.impl.FileSystemSlideManager.java
/** * This method create thumbImage of the image file given and save it in outFile. * Compression quality is also given. thumbBounds is used for calculating the size of the thumb. * //from w w w.ja va 2 s. c om * @param infile slide image to create thumb * @param outfile output thumb file * @param compressionQuality the compression quality * @param thumbBounds the thumb bounds * * @throws IOException Signals that an I/O exception has occurred. */ public void resizeImage(File infile, File outfile, float compressionQuality, int thumbBounds) throws IOException { // Retrieve jpg image to be resized Image image = ImageIO.read(infile); // get original image size for thumb size calculation int imageWidth = image.getWidth(null); int imageHeight = image.getHeight(null); float thumbRatio = (float) thumbBounds / Math.max(imageWidth, imageHeight); int thumbWidth = (int) (imageWidth * thumbRatio); int thumbHeight = (int) (imageHeight * thumbRatio); // draw original image to thumbnail image object and // scale it to the new size on-the-fly BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB); Graphics2D graphics2D = thumbImage.createGraphics(); graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null); // Find a jpeg writer ImageWriter writer = null; Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpg"); if (iter.hasNext()) { writer = (ImageWriter) iter.next(); } ImageWriteParam iwp = writer.getDefaultWriteParam(); iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); iwp.setCompressionQuality(compressionQuality); // Prepare output file ImageOutputStream ios = ImageIO.createImageOutputStream(outfile); writer.setOutput(ios); // write to the thumb image writer.write(thumbImage); // Cleanup ios.flush(); writer.dispose(); ios.close(); }
From source file:org.freecine.filmscan.Project.java
private void saveImage(RenderedImage img, File file) { // Find a writer for that file extensions // Try to determine the file type based on extension String ftype = "jpg"; String imageFname = file.getName(); int extIndex = imageFname.lastIndexOf(".") + 1; if (extIndex > 0) { ftype = imageFname.substring(extIndex); }// w ww .j ava2 s. c o m ImageWriter writer = null; Iterator iter = ImageIO.getImageWritersBySuffix(ftype); writer = (ImageWriter) iter.next(); if (writer != null) { ImageOutputStream ios = null; try { // Prepare output file ios = ImageIO.createImageOutputStream(file); writer.setOutput(ios); // Set some parameters ImageWriteParam param = writer.getDefaultWriteParam(); writer.write(null, new IIOImage(img, null, null), param); // Cleanup ios.flush(); } catch (IOException ex) { log.severe("Error saving image " + file.getAbsolutePath() + ": " + ex.getMessage()); } finally { if (ios != null) { try { ios.close(); } catch (IOException e) { log.severe("Error closing output stream: " + e.getMessage()); } } writer.dispose(); } } }
From source file:org.geoserver.wps.gs.download.RasterDownload.java
/** * Writes the providede GridCoverage as a GeoTiff file. * //from w w w. j a v a2s. com * @param mimeType result mimetype * @param coverageInfo resource associated to the input coverage * @param gridCoverage gridcoverage to write * @return a {@link File} that points to the GridCoverage we wrote. * */ private Resource writeRaster(String mimeType, CoverageInfo coverageInfo, GridCoverage2D gridCoverage) throws Exception { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Writing raster"); } // limits long limit = DownloadServiceConfiguration.NO_LIMIT; if (limits.getHardOutputLimit() > 0) { limit = limits.getHardOutputLimit(); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Hard output limits set to " + limit); } } else { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Hard output limit unset"); } } // Search a proper PPIO Parameter<GridCoverage2D> gridParam = new Parameter<GridCoverage2D>("fakeParam", GridCoverage2D.class); ProcessParameterIO ppio_ = DownloadUtilities.find(gridParam, context, mimeType, false); if (ppio_ == null) { throw new ProcessException("Don't know how to encode in mime type " + mimeType); } else if (!(ppio_ instanceof ComplexPPIO)) { throw new ProcessException("Invalid PPIO found " + ppio_.getIdentifer()); } final ComplexPPIO complexPPIO = (ComplexPPIO) ppio_; String extension = complexPPIO.getFileExtension(); // writing the output to a temporary folder if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Writing file in a temporary folder"); } final Resource output = resourceManager.getTemporaryResource("." + extension); // the limit output stream will throw an exception if the process is trying to writer more than the max allowed bytes final ImageOutputStream fileImageOutputStreamExtImpl = new ImageOutputStreamAdapter(output.out()); ImageOutputStream os = null; // write try { // If limit is defined, LimitedImageOutputStream is used if (limit > DownloadServiceConfiguration.NO_LIMIT) { os = new LimitedImageOutputStream(fileImageOutputStreamExtImpl, limit) { @Override protected void raiseError(long pSizeMax, long pCount) throws IOException { IOException e = new IOException("Download Exceeded the maximum HARD allowed size!"); throw e; } }; } else { os = fileImageOutputStreamExtImpl; } // Encoding the GridCoverage complexPPIO.encode(gridCoverage, new OutputStreamAdapter(os)); os.flush(); } finally { try { if (os != null) { os.close(); } } catch (Exception e) { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, e.getLocalizedMessage(), e); } } } return output; }
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>//www . j a v a2s . 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>/* w w w . j a va2s . 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 */ }