List of usage examples for javax.imageio.stream ImageOutputStream close
void close() throws IOException;
From source file:net.rptools.tokentool.AppActions.java
public static void saveToken(File rptok_file, boolean overwrite) { if (rptok_file != null) { if (!rptok_file.getName().toUpperCase().endsWith(".RPTOK")) { rptok_file = new File(rptok_file.getAbsolutePath() + ".rptok"); }/*from w w w .j av a2 s .c o m*/ if (rptok_file.exists() && !overwrite) { if (!TokenTool.confirm("File exists. Overwrite?")) { return; } else { rptok_file.delete(); } } String tokenName = FilenameUtils.removeExtension(rptok_file.getName()); try { // Write out the token image first or aka POG image. File tokenImageFile = File.createTempFile("tokenImage", ".png"); // PW: This code addes the pHYs chunk to the // output png file with X & Y dpi set. BufferedImage tokenImg = TokenTool.getFrame().getComposedToken(); BufferedImage portraitImg = TokenTool.getFrame().getTokenCompositionPanel().getBaseImage(); ImageWriter writer = getImageWriterBySuffix("png"); // Created object for outputStream so we can properly close it! No longer locks .png files until app closes! ImageOutputStream ios = ImageIO.createImageOutputStream(tokenImageFile); writer.setOutput(ios); ImageWriteParam param = writer.getDefaultWriteParam(); PNGMetadata png = new PNGMetadata(); // 39.375 inches per meter // I'm using the image width for the DPI under // the assumption that the token fits within // one cell. int resX = (int) (tokenImg.getWidth() * 39.375f); png.pHYs_pixelsPerUnitXAxis = resX; png.pHYs_pixelsPerUnitYAxis = resX; png.pHYs_unitSpecifier = 1; // Meters - alternative is "unknown" png.pHYs_present = true; writer.write(null, new IIOImage(tokenImg, null, png), param); ios.close(); // Now write out the Portrait image, here we'll use JPEG to save space File portraitImageFile = File.createTempFile("portraitImage", ".jpg"); writer.reset(); writer = getImageWriterBySuffix("jpg"); ios = ImageIO.createImageOutputStream(portraitImageFile); writer.setOutput(ios); param = writer.getDefaultWriteParam(); writer.write(null, new IIOImage(portraitImg, null, null), param); writer.dispose(); ios.close(); // Lets create the token! Token _token = new Token(); Asset tokenImage = null; tokenImage = AssetManager.createAsset(tokenImageFile); AssetManager.putAsset(tokenImage); _token = new Token(tokenName, tokenImage.getId()); _token.setGMName(tokenName); // Jamz: Below calls not needed, creates extra entries in XML preventing token image from changing inside MapTool //_token.setImageAsset(tokenImage.getName()); //_token.setImageAsset(tokenImage.getName(), tokenImage.getId()); // set the image shape Image image = ImageIO.read(tokenImageFile); _token.setShape(TokenUtil.guessTokenType(image)); // set the height/width, fixes dragging to stamp layer issue _token.setHeight(tokenImg.getHeight()); _token.setWidth(tokenImg.getWidth()); // set the portrait image asset Asset portrait = AssetManager.createAsset(portraitImageFile); // Change for portrait AssetManager.putAsset(portrait); _token.setPortraitImage(portrait.getId()); // Time to write out the .rptok token file... PackedFile pakFile = null; try { pakFile = new PackedFile(rptok_file); saveAssets(_token.getAllImageAssets(), pakFile); pakFile.setContent(_token); BufferedImage thumb = ImageUtil.createCompatibleImage(image, THUMB_SIZE, THUMB_SIZE, null); pakFile.putFile(FILE_THUMBNAIL, ImageUtil.imageToBytes(thumb, "png")); pakFile.setProperty(PROP_VERSION, TokenToolFrame.VERSION); pakFile.save(); } catch (Exception e) { e.printStackTrace(); } finally { if (pakFile != null) pakFile.close(); tokenImageFile.delete(); portraitImageFile.delete(); } } catch (IOException ioe) { ioe.printStackTrace(); TokenTool.showError("Unable to write image: " + ioe); } } }
From source file:compressor.Compressor.java
void compress_images(String src, String dest) throws IOException { File f = null;/*from w ww .j a va 2 s . c o m*/ String[] paths; try { // create new file f = new File(src); // array of files and directory paths = f.list(); File file = new File(dest + "compressed"); if (!file.exists()) { if (file.mkdir()) { System.out.println("Directory is created!"); } else { System.out.println("Failed to create directory!"); } } dest = dest + "compressed/"; // for each name in the path array for (String path : paths) { // prints filename and directory name File input = new File(src + path); BufferedImage image = ImageIO.read(input); File compressedImageFile = new File(dest + path); OutputStream os = new FileOutputStream(compressedImageFile); Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg"); ImageWriter writer = (ImageWriter) writers.next(); ImageOutputStream ios = ImageIO.createImageOutputStream(os); writer.setOutput(ios); ImageWriteParam param = writer.getDefaultWriteParam(); param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); param.setCompressionQuality(0.05f); writer.write(null, new IIOImage(image, null, null), param); os.close(); ios.close(); writer.dispose(); } } catch (Exception e) { } }
From source file:com.alkacon.opencms.v8.weboptimization.CmsOptimizationSprite.java
/** * Writes the given image as of the given type to the servlet output stream.<p> * //from ww w . j av a 2 s. c o m * @param image the image to write * @param type the type * * @throws IOException if something goes wrong */ protected void writeImage(BufferedImage image, String type) throws IOException { ImageWriter writer = (ImageWriter) ImageIO.getImageWritersByFormatName(type).next(); ImageOutputStream stream = ImageIO.createImageOutputStream(getJspContext().getResponse().getOutputStream()); writer.setOutput(stream); writer.write(image); // We must close the stream now because if we are wrapping a ServletOutputStream, // a future gc can commit a stream that used in another thread (very very bad) stream.flush(); stream.close(); writer.dispose(); }
From source file:net.d53dev.dslfy.web.service.GifService.java
public void saveAnimatedGIF(OutputStream out, List<GifFrame> frames, int loopCount) throws Exception { ImageWriter iw = ImageIO.getImageWritersByFormatName("gif").next(); ImageOutputStream ios = ImageIO.createImageOutputStream(out); iw.setOutput(ios);//from w ww. java 2 s. co m iw.prepareWriteSequence(null); int p = 0; for (GifFrame frame : frames) { ImageWriteParam iwp = iw.getDefaultWriteParam(); IIOMetadata metadata = iw.getDefaultImageMetadata(new ImageTypeSpecifier(frame.img), iwp); this.configureGIFFrame(metadata, String.valueOf(frame.delay / 10L), p++, frame.disposalMethod, loopCount); IIOImage ii = new IIOImage(frame.img, null, metadata); iw.writeToSequence(ii, null); } iw.endWriteSequence(); ios.close(); }
From source file:jails.http.converter.BufferedImageHttpMessageConverter.java
public void write(BufferedImage image, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { if (contentType == null) { contentType = getDefaultContentType(); }//from ww w . j a v a2s .com Assert.notNull(contentType, "Count not determine Content-Type, set one using the 'defaultContentType' property"); outputMessage.getHeaders().setContentType(contentType); ImageOutputStream imageOutputStream = null; ImageWriter imageWriter = null; try { imageOutputStream = createImageOutputStream(outputMessage.getBody()); Iterator<ImageWriter> imageWriters = ImageIO.getImageWritersByMIMEType(contentType.toString()); if (imageWriters.hasNext()) { imageWriter = imageWriters.next(); ImageWriteParam iwp = imageWriter.getDefaultWriteParam(); process(iwp); imageWriter.setOutput(imageOutputStream); imageWriter.write(null, new IIOImage(image, null, null), iwp); } else { throw new HttpMessageNotWritableException( "Could not find javax.imageio.ImageWriter for Content-Type [" + contentType + "]"); } } finally { if (imageWriter != null) { imageWriter.dispose(); } if (imageOutputStream != null) { try { imageOutputStream.close(); } catch (IOException ex) { // ignore } } } }
From source file:de.unigoettingen.sub.commons.contentlib.imagelib.JpegInterpreter.java
@Override public byte[] writeToStreamAndByteArray(OutputStream outStream) { byte[] data = null; if (this.renderedimage == null) { // no image available return data; }/*from ww w.j a v a 2 s .c o m*/ try { // create a buffered Image, which has no Alpha channel // as JPEG does not support Alpha Channels and the // ImageIO doesn't care - but will create a corrupt JPEG BufferedImage noAlphaBi = ImageManipulator.fromRenderedToBufferedNoAlpha(renderedimage); ImageOutputStream imageOutStream = ImageIO.createImageOutputStream(outStream); // Iterator<ImageWriter> writerIter = ImageIO // .getImageWritersByFormatName("jpg"); // ImageWriter writer = writerIter.next(); // get writer from ImageIO ImageWriter writer = new JPEGImageWriter(new JPEGImageWriterSpi()); // create metadata by creating an XML tree ImageWriteParam writerParam = writer.getDefaultWriteParam(); ImageTypeSpecifier its = new ImageTypeSpecifier(noAlphaBi); // ImageTypeSpecifier its = new // ImageTypeSpecifier(image.getColorModel(), // image.getSampleModel()); // IIOMetadata iomd = writer.getDefaultImageMetadata(new // ImageTypeSpecifier(image), writerParam); // Element tree = // (Element)iomd.getAsTree("javax_imageio_jpeg_image_1.0"); // Element tree = (Element)iomd.getAsTree("javax_imageio_1.0"); // IIOMetadata iomd = writer.getDefaultImageMetadata(its, writerParam); // create the XML tree and modify the appropriate DOM elements // to set the metadata setMetadata(iomd); // set compression writerParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); float comprvalue = ((float) writerCompressionValue) / 100; writerParam.setCompressionQuality(comprvalue); // set output writer.setOutput(imageOutStream); writer.prepareWriteSequence(null); // create new image parameters to set the compression // Locale locale = new Locale("en"); // JPEGImageWriteParam jpegWriteParam = new // JPEGImageWriteParam(locale); // IIOImage iioImage = new IIOImage(renderedimage, null, iomd); IIOImage iioImage = new IIOImage(noAlphaBi, null, iomd); writer.write(null, iioImage, writerParam); writer.endWriteSequence(); imageOutStream.flush(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageOutputStream imageToFile = ImageIO.createImageOutputStream(baos); writer.setOutput(imageToFile); writer.prepareWriteSequence(null); writer.write(null, iioImage, writerParam); writer.endWriteSequence(); imageToFile.flush(); imageToFile.close(); baos.flush(); data = baos.toByteArray(); baos.close(); writer.dispose(); imageOutStream.close(); } catch (IOException e) { LOGGER.error("IOException occured", e); } return data; }
From source file:de.unigoettingen.sub.commons.contentlib.imagelib.JpegInterpreter.java
/************************************************************************************ * Write the renderedimage to an {@link OutputStream} * /*w w w . ja v a 2 s.c o m*/ * @param outStream the {@link OutputStream} to write to ************************************************************************************/ @Override public void writeToStream(FileOutputStream fos, OutputStream outStream) { if (this.renderedimage == null) { // no image available return; } try { // create a buffered Image, which has no Alpha channel // as JPEG does not support Alpha Channels and the // ImageIO doesn't care - but will create a corrupt JPEG BufferedImage noAlphaBi = ImageManipulator.fromRenderedToBufferedNoAlpha(renderedimage); ImageOutputStream imageOutStream = ImageIO.createImageOutputStream(outStream); // Iterator<ImageWriter> writerIter = ImageIO // .getImageWritersByFormatName("jpg"); // ImageWriter writer = writerIter.next(); // get writer from ImageIO ImageWriter writer = new JPEGImageWriter(new JPEGImageWriterSpi()); // create metadata by creating an XML tree ImageWriteParam writerParam = writer.getDefaultWriteParam(); ImageTypeSpecifier its = new ImageTypeSpecifier(noAlphaBi); // ImageTypeSpecifier its = new // ImageTypeSpecifier(image.getColorModel(), // image.getSampleModel()); // IIOMetadata iomd = writer.getDefaultImageMetadata(new // ImageTypeSpecifier(image), writerParam); // Element tree = // (Element)iomd.getAsTree("javax_imageio_jpeg_image_1.0"); // Element tree = (Element)iomd.getAsTree("javax_imageio_1.0"); // IIOMetadata iomd = writer.getDefaultImageMetadata(its, writerParam); // create the XML tree and modify the appropriate DOM elements // to set the metadata setMetadata(iomd); // set compression writerParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); float comprvalue = ((float) writerCompressionValue) / 100; writerParam.setCompressionQuality(comprvalue); // set output writer.setOutput(imageOutStream); writer.prepareWriteSequence(null); // create new image parameters to set the compression // Locale locale = new Locale("en"); // JPEGImageWriteParam jpegWriteParam = new // JPEGImageWriteParam(locale); // IIOImage iioImage = new IIOImage(renderedimage, null, iomd); IIOImage iioImage = new IIOImage(noAlphaBi, null, iomd); writer.write(null, iioImage, writerParam); writer.endWriteSequence(); imageOutStream.flush(); if (fos != null) { ImageOutputStream imageToFile = ImageIO.createImageOutputStream(fos); writer.setOutput(imageToFile); writer.prepareWriteSequence(null); writer.write(null, iioImage, writerParam); writer.endWriteSequence(); imageToFile.flush(); imageToFile.close(); fos.flush(); fos.close(); } // ByteArrayOutputStream baos = new ByteArrayOutputStream(); // byte [] data = wi.getImageAsByteArray(); writer.dispose(); imageOutStream.close(); } catch (IOException e) { LOGGER.error("IOException occured", e); } }
From source file:edu.ku.brc.specify.utilapps.ERDVisualizer.java
public void writeJPEG(File outfile, BufferedImage bufferedImage, float compressionQuality) { try {//from w ww.j av a 2 s .c om long start = System.currentTimeMillis(); // Find a jpeg writer ImageWriter writer = null; Iterator<?> iter = ImageIO.getImageWritersByFormatName("jpg"); if (iter.hasNext()) { writer = (ImageWriter) iter.next(); } // Prepare output file ImageOutputStream ios = ImageIO.createImageOutputStream(outfile); writer.setOutput(ios); // Set the compression quality ImageWriteParam iwparam = new MyImageWriteParam(); iwparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); iwparam.setCompressionQuality(compressionQuality); // Write the image writer.write(null, new IIOImage(bufferedImage, null, null), null); // Cleanup ios.flush(); writer.dispose(); ios.close(); System.out.println(System.currentTimeMillis() - start); } catch (IOException e) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ERDVisualizer.class, e); e.printStackTrace(); } }
From source file:com.lingxiang2014.util.ImageUtils.java
public static void zoom(File srcFile, File destFile, int destWidth, int destHeight) { Assert.notNull(srcFile);// w ww.j av a2 s. co m Assert.notNull(destFile); Assert.state(destWidth > 0); Assert.state(destHeight > 0); if (type == Type.jdk) { Graphics2D graphics2D = null; ImageOutputStream imageOutputStream = null; ImageWriter imageWriter = null; try { BufferedImage srcBufferedImage = ImageIO.read(srcFile); int srcWidth = srcBufferedImage.getWidth(); int srcHeight = srcBufferedImage.getHeight(); int width = destWidth; int height = destHeight; if (srcHeight >= srcWidth) { width = (int) Math.round(((destHeight * 1.0 / srcHeight) * srcWidth)); } else { height = (int) Math.round(((destWidth * 1.0 / srcWidth) * srcHeight)); } BufferedImage destBufferedImage = new BufferedImage(destWidth, destHeight, BufferedImage.TYPE_INT_RGB); graphics2D = destBufferedImage.createGraphics(); graphics2D.setBackground(BACKGROUND_COLOR); graphics2D.clearRect(0, 0, destWidth, destHeight); graphics2D.drawImage(srcBufferedImage.getScaledInstance(width, height, Image.SCALE_SMOOTH), (destWidth / 2) - (width / 2), (destHeight / 2) - (height / 2), null); imageOutputStream = ImageIO.createImageOutputStream(destFile); imageWriter = ImageIO.getImageWritersByFormatName(FilenameUtils.getExtension(destFile.getName())) .next(); imageWriter.setOutput(imageOutputStream); ImageWriteParam imageWriteParam = imageWriter.getDefaultWriteParam(); imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); imageWriteParam.setCompressionQuality((float) (DEST_QUALITY / 100.0)); imageWriter.write(null, new IIOImage(destBufferedImage, null, null), imageWriteParam); imageOutputStream.flush(); } catch (IOException e) { e.printStackTrace(); } finally { if (graphics2D != null) { graphics2D.dispose(); } if (imageWriter != null) { imageWriter.dispose(); } if (imageOutputStream != null) { try { imageOutputStream.close(); } catch (IOException e) { } } } } else { IMOperation operation = new IMOperation(); operation.thumbnail(destWidth, destHeight); operation.gravity("center"); operation.background(toHexEncoding(BACKGROUND_COLOR)); operation.extent(destWidth, destHeight); operation.quality((double) DEST_QUALITY); operation.addImage(srcFile.getPath()); operation.addImage(destFile.getPath()); if (type == Type.graphicsMagick) { ConvertCmd convertCmd = new ConvertCmd(true); if (graphicsMagickPath != null) { convertCmd.setSearchPath(graphicsMagickPath); } try { convertCmd.run(operation); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } catch (IM4JavaException e) { e.printStackTrace(); } } else { ConvertCmd convertCmd = new ConvertCmd(false); if (imageMagickPath != null) { convertCmd.setSearchPath(imageMagickPath); } try { convertCmd.run(operation); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } catch (IM4JavaException e) { e.printStackTrace(); } } } }