Example usage for javax.imageio ImageWriter write

List of usage examples for javax.imageio ImageWriter write

Introduction

In this page you can find the example usage for javax.imageio ImageWriter write.

Prototype

public abstract void write(IIOMetadata streamMetadata, IIOImage image, ImageWriteParam param)
        throws IOException;

Source Link

Document

Appends a complete image stream containing a single image and associated stream and image metadata and thumbnails to the output.

Usage

From source file:org.dcm4che2.tool.dcm2jpg.Dcm2Jpg.java

private void encodeByImageIO(BufferedImage bi, File dest) throws IOException {
    ImageWriter writer = getImageWriter(imageWriterClassname);
    ImageOutputStream out = null;
    try {/*from www.  j av a  2 s .c o m*/
        out = ImageIO.createImageOutputStream(dest);
        writer.setOutput(out);
        ImageWriteParam iwparam = writer.getDefaultWriteParam();
        if (iwparam.canWriteCompressed()) {
            iwparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            String[] compressionTypes = iwparam.getCompressionTypes();
            if (compressionTypes != null && compressionTypes.length > 0) {
                if (compressionType != null || iwparam.getCompressionType() == null) {
                    for (int i = 0; i < compressionTypes.length; i++) {
                        if (compressionType == null
                                || compressionTypes[i].compareToIgnoreCase(compressionType) == 0) {
                            iwparam.setCompressionType(compressionTypes[i]);
                            break;
                        }
                    }
                }
            }
            if (imageQuality != null)
                iwparam.setCompressionQuality(imageQuality);
        } else if (imageQuality != null) {
            System.out.println("Selected Image Writer can not compress! imageQuality is ignored!");
        }
        writer.write(null, new IIOImage(bi, null, null), iwparam);
    } finally {
        CloseUtils.safeClose(out);
        writer.dispose();
    }
}

From source file:org.eclipse.birt.chart.device.svg.SVGGraphics2D.java

private Element createEmbeddeImage(BufferedImage img) {
    if (img == null) {
        return null;
    }//from  w  w w  . j  av  a 2  s.  c  o  m

    int width = img.getWidth();
    int height = img.getHeight();
    ImageWriter iw = ImageWriterFactory.instance().createByFormatName("png"); //$NON-NLS-1$
    ByteArrayOutputStream baos = new ByteArrayOutputStream(8192 * 2);
    String sUrl = null;
    try {
        final ImageOutputStream ios = SecurityUtil.newImageOutputStream(baos);
        ImageWriteParam iwp = iw.getDefaultWriteParam();
        iw.setOutput(ios);
        iw.write((IIOMetadata) null, new IIOImage(img, null, null), iwp);
        img.flush();
        ios.close();
        sUrl = SVGImage.BASE64 + new String(Base64.encodeBase64(baos.toByteArray()));
    } catch (Exception ex) {
        logger.log(ex);
    } finally {
        iw.dispose();
    }

    Element elemG = dom.createElement("g"); //$NON-NLS-1$
    elemG.setAttribute("id", "img_" + img.hashCode()); //$NON-NLS-1$//$NON-NLS-2$
    Element elem = dom.createElement("image"); //$NON-NLS-1$
    elem.setAttribute("x", "0"); //$NON-NLS-1$//$NON-NLS-2$
    elem.setAttribute("y", "0"); //$NON-NLS-1$ //$NON-NLS-2$
    elem.setAttribute("width", Integer.toString(width)); //$NON-NLS-1$
    elem.setAttribute("height", Integer.toString(height)); //$NON-NLS-1$
    elem.setAttribute("xlink:href", sUrl); //$NON-NLS-1$
    elemG.appendChild(elem);

    return elemG;
}

From source file:net.groupbuy.util.ImageUtils.java

/**
 * ?/*from  w w w.jav  a2  s.  co  m*/
 * 
 * @param srcFile
 *            ?
 * @param destFile
 *            
 * @param watermarkFile
 *            ?
 * @param watermarkPosition
 *            ??
 * @param alpha
 *            ??
 */
public static void addWatermark(File srcFile, File destFile, File watermarkFile,
        WatermarkPosition watermarkPosition, int alpha) {
    Assert.notNull(srcFile);
    Assert.notNull(destFile);
    Assert.state(alpha >= 0);
    Assert.state(alpha <= 100);
    if (watermarkFile == null || !watermarkFile.exists() || watermarkPosition == null
            || watermarkPosition == WatermarkPosition.no) {
        try {
            FileUtils.copyFile(srcFile, destFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return;
    }
    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();
            BufferedImage destBufferedImage = new BufferedImage(srcWidth, srcHeight,
                    BufferedImage.TYPE_INT_RGB);
            graphics2D = destBufferedImage.createGraphics();
            graphics2D.setBackground(BACKGROUND_COLOR);
            graphics2D.clearRect(0, 0, srcWidth, srcHeight);
            graphics2D.drawImage(srcBufferedImage, 0, 0, null);
            graphics2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha / 100F));

            BufferedImage watermarkBufferedImage = ImageIO.read(watermarkFile);
            int watermarkImageWidth = watermarkBufferedImage.getWidth();
            int watermarkImageHeight = watermarkBufferedImage.getHeight();
            int x = srcWidth - watermarkImageWidth;
            int y = srcHeight - watermarkImageHeight;
            if (watermarkPosition == WatermarkPosition.topLeft) {
                x = 0;
                y = 0;
            } else if (watermarkPosition == WatermarkPosition.topRight) {
                x = srcWidth - watermarkImageWidth;
                y = 0;
            } else if (watermarkPosition == WatermarkPosition.center) {
                x = (srcWidth - watermarkImageWidth) / 2;
                y = (srcHeight - watermarkImageHeight) / 2;
            } else if (watermarkPosition == WatermarkPosition.bottomLeft) {
                x = 0;
                y = srcHeight - watermarkImageHeight;
            } else if (watermarkPosition == WatermarkPosition.bottomRight) {
                x = srcWidth - watermarkImageWidth;
                y = srcHeight - watermarkImageHeight;
            }
            graphics2D.drawImage(watermarkBufferedImage, x, y, watermarkImageWidth, watermarkImageHeight, 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(DEST_QUALITY / 100F);
            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 {
        String gravity = "SouthEast";
        if (watermarkPosition == WatermarkPosition.topLeft) {
            gravity = "NorthWest";
        } else if (watermarkPosition == WatermarkPosition.topRight) {
            gravity = "NorthEast";
        } else if (watermarkPosition == WatermarkPosition.center) {
            gravity = "Center";
        } else if (watermarkPosition == WatermarkPosition.bottomLeft) {
            gravity = "SouthWest";
        } else if (watermarkPosition == WatermarkPosition.bottomRight) {
            gravity = "SouthEast";
        }
        IMOperation operation = new IMOperation();
        operation.gravity(gravity);
        operation.dissolve(alpha);
        operation.quality((double) DEST_QUALITY);
        operation.addImage(watermarkFile.getPath());
        operation.addImage(srcFile.getPath());
        operation.addImage(destFile.getPath());
        if (type == Type.graphicsMagick) {
            CompositeCmd compositeCmd = new CompositeCmd(true);
            if (graphicsMagickPath != null) {
                compositeCmd.setSearchPath(graphicsMagickPath);
            }
            try {
                compositeCmd.run(operation);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (IM4JavaException e) {
                e.printStackTrace();
            }
        } else {
            CompositeCmd compositeCmd = new CompositeCmd(false);
            if (imageMagickPath != null) {
                compositeCmd.setSearchPath(imageMagickPath);
            }
            try {
                compositeCmd.run(operation);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (IM4JavaException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:com.el.ecom.utils.ImageUtils.java

/**
 * ?/* w w w . j  a  v a 2s  .c o  m*/
 * 
 * @param srcFile ?
 * @param destFile 
 * @param watermarkFile ?
 * @param watermarkPosition ??
 * @param alpha ??
 */
public static void addWatermark(File srcFile, File destFile, File watermarkFile,
        WatermarkPosition watermarkPosition, int alpha) {
    Assert.notNull(srcFile);
    Assert.state(srcFile.exists());
    Assert.state(srcFile.isFile());
    Assert.notNull(destFile);
    Assert.state(alpha >= 0);
    Assert.state(alpha <= 100);

    if (watermarkFile == null || !watermarkFile.exists() || !watermarkFile.isFile() || watermarkPosition == null
            || watermarkPosition == WatermarkPosition.no) {
        try {
            if (!StringUtils.equals(srcFile.getCanonicalPath(), destFile.getCanonicalPath())) {
                FileUtils.copyFile(srcFile, destFile);
            }
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        return;
    }
    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();
            BufferedImage destBufferedImage = new BufferedImage(srcWidth, srcHeight,
                    BufferedImage.TYPE_INT_RGB);
            graphics2D = destBufferedImage.createGraphics();
            graphics2D.setBackground(BACKGROUND_COLOR);
            graphics2D.clearRect(0, 0, srcWidth, srcHeight);
            graphics2D.drawImage(srcBufferedImage, 0, 0, null);
            graphics2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha / 100F));

            BufferedImage watermarkBufferedImage = ImageIO.read(watermarkFile);
            int watermarkImageWidth = watermarkBufferedImage.getWidth();
            int watermarkImageHeight = watermarkBufferedImage.getHeight();
            int x = srcWidth - watermarkImageWidth;
            int y = srcHeight - watermarkImageHeight;
            if (watermarkPosition == WatermarkPosition.topLeft) {
                x = 0;
                y = 0;
            } else if (watermarkPosition == WatermarkPosition.topRight) {
                x = srcWidth - watermarkImageWidth;
                y = 0;
            } else if (watermarkPosition == WatermarkPosition.center) {
                x = (srcWidth - watermarkImageWidth) / 2;
                y = (srcHeight - watermarkImageHeight) / 2;
            } else if (watermarkPosition == WatermarkPosition.bottomLeft) {
                x = 0;
                y = srcHeight - watermarkImageHeight;
            } else if (watermarkPosition == WatermarkPosition.bottomRight) {
                x = srcWidth - watermarkImageWidth;
                y = srcHeight - watermarkImageHeight;
            }
            graphics2D.drawImage(watermarkBufferedImage, x, y, watermarkImageWidth, watermarkImageHeight, 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(DEST_QUALITY / 100F);
            imageWriter.write(null, new IIOImage(destBufferedImage, null, null), imageWriteParam);
            imageOutputStream.flush();
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        } finally {
            if (graphics2D != null) {
                graphics2D.dispose();
            }
            if (imageWriter != null) {
                imageWriter.dispose();
            }
            try {
                if (imageOutputStream != null) {
                    imageOutputStream.close();
                }
            } catch (IOException e) {
            }
        }
    } else {
        String gravity = "SouthEast";
        if (watermarkPosition == WatermarkPosition.topLeft) {
            gravity = "NorthWest";
        } else if (watermarkPosition == WatermarkPosition.topRight) {
            gravity = "NorthEast";
        } else if (watermarkPosition == WatermarkPosition.center) {
            gravity = "Center";
        } else if (watermarkPosition == WatermarkPosition.bottomLeft) {
            gravity = "SouthWest";
        } else if (watermarkPosition == WatermarkPosition.bottomRight) {
            gravity = "SouthEast";
        }
        IMOperation operation = new IMOperation();
        operation.gravity(gravity);
        operation.dissolve(alpha);
        operation.quality((double) DEST_QUALITY);
        try {
            operation.addImage(watermarkFile.getCanonicalPath());
            operation.addImage(srcFile.getCanonicalPath());
            operation.addImage(destFile.getCanonicalPath());
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        if (type == Type.graphicsMagick) {
            CompositeCmd compositeCmd = new CompositeCmd(true);
            if (graphicsMagickPath != null) {
                compositeCmd.setSearchPath(graphicsMagickPath);
            }
            try {
                compositeCmd.run(operation);
            } catch (IOException e) {
                throw new RuntimeException(e.getMessage(), e);
            } catch (InterruptedException e) {
                throw new RuntimeException(e.getMessage(), e);
            } catch (IM4JavaException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        } else {
            CompositeCmd compositeCmd = new CompositeCmd(false);
            if (imageMagickPath != null) {
                compositeCmd.setSearchPath(imageMagickPath);
            }
            try {
                compositeCmd.run(operation);
            } catch (IOException e) {
                throw new RuntimeException(e.getMessage(), e);
            } catch (InterruptedException e) {
                throw new RuntimeException(e.getMessage(), e);
            } catch (IM4JavaException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        }
    }
}

From source file:com.ackpdfbox.app.imageio.ImageIOUtil.java

/**
 * Writes a buffered image to a file using the given image format.
 * Compression is fixed for PNG, GIF, BMP and WBMP, dependent of the quality
 * parameter for JPG, and dependent of bit count for TIFF (a bitonal image
 * will be compressed with CCITT G4, a color image with LZW). Creating a
 * TIFF image is only supported if the jai_imageio library is in the class
 * path.// ww  w. jav  a  2s.com
 *
 * @param image the image to be written
 * @param formatName the target format (ex. "png")
 * @param output the output stream to be used for writing
 * @param dpi the resolution in dpi (dots per inch) to be used in metadata
 * @param quality quality to be used when compressing the image (0 &lt;
 * quality &lt; 1.0f)
 * @return true if the image file was produced, false if there was an error.
 * @throws IOException if an I/O error occurs
 */
public static boolean writeImage(BufferedImage image, String formatName, OutputStream output, int dpi,
        float quality) throws IOException {
    ImageOutputStream imageOutput = null;
    ImageWriter writer = null;
    try {
        // find suitable image writer
        Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(formatName);
        ImageWriteParam param = null;
        IIOMetadata metadata = null;
        // Loop until we get the best driver, i.e. one that supports
        // setting dpi in the standard metadata format; however we'd also 
        // accept a driver that can't, if a better one can't be found
        while (writers.hasNext()) {
            if (writer != null) {
                writer.dispose();
            }
            writer = writers.next();
            param = writer.getDefaultWriteParam();
            metadata = writer.getDefaultImageMetadata(new ImageTypeSpecifier(image), param);
            if (metadata != null && !metadata.isReadOnly() && metadata.isStandardMetadataFormatSupported()) {
                break;
            }
        }
        if (writer == null) {
            LOG.error("No ImageWriter found for '" + formatName + "' format");
            StringBuilder sb = new StringBuilder();
            String[] writerFormatNames = ImageIO.getWriterFormatNames();
            for (String fmt : writerFormatNames) {
                sb.append(fmt);
                sb.append(' ');
            }
            LOG.error("Supported formats: " + sb);
            return false;
        }

        // compression
        if (param != null && param.canWriteCompressed()) {
            param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            if (formatName.toLowerCase().startsWith("tif")) {
                // TIFF compression
                TIFFUtil.setCompressionType(param, image);
            } else {
                param.setCompressionType(param.getCompressionTypes()[0]);
                param.setCompressionQuality(quality);
            }
        }

        if (formatName.toLowerCase().startsWith("tif")) {
            // TIFF metadata
            TIFFUtil.updateMetadata(metadata, image, dpi);
        } else if ("jpeg".equals(formatName.toLowerCase()) || "jpg".equals(formatName.toLowerCase())) {
            // This segment must be run before other meta operations,
            // or else "IIOInvalidTreeException: Invalid node: app0JFIF"
            // The other (general) "meta" methods may not be used, because
            // this will break the reading of the meta data in tests
            JPEGUtil.updateMetadata(metadata, dpi);
        } else {
            // write metadata is possible
            if (metadata != null && !metadata.isReadOnly() && metadata.isStandardMetadataFormatSupported()) {
                setDPI(metadata, dpi, formatName);
            }
        }

        // write
        imageOutput = ImageIO.createImageOutputStream(output);
        writer.setOutput(imageOutput);
        writer.write(null, new IIOImage(image, null, metadata), param);
    } finally {
        if (writer != null) {
            writer.dispose();
        }
        if (imageOutput != null) {
            imageOutput.close();
        }
    }
    return true;
}

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  w w w .j  a v  a  2  s .  c om
    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 ww. j a 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:org.getobjects.appserver.publisher.GoDefaultRenderer.java

/**
 * Renders a java.awt.BufferedImage to the WOResponse of the given context.
 * Remember to configure:<pre>/* w  w w.  j  a v  a 2s .  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 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.jav a 2s . 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:nl.softwaredesign.exporter.ODTExportFormat.java

/**
 * TODO Move to utility class?/*from w  w w  .  java 2s .co  m*/
 * Extract the content data (bytes) from the given image.
 * @param icon image to get bytes for
 * @param format desired format for image
 * @param background Color to use as background if transparency in image
 * @param width Desired width of the image in the byte array
 * @param height Desired width of the image in the byte array
 * @return the bytes of the image
 * @throws IOException
 */
private byte[] imageToBytes(ImageIcon icon, String format, Color background, int width, int height)
        throws IOException {
    Iterator writers = ImageIO.getImageWritersByFormatName(format);
    ImageWriter writer = (ImageWriter) writers.next();
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    ImageOutputStream ios = ImageIO.createImageOutputStream(output);
    writer.setOutput(ios);
    BufferedImage img;
    if ("png".equalsIgnoreCase(format) || "gif".equalsIgnoreCase(format)) {
        img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    } else {
        img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    }
    WaitingObserver observer = new WaitingObserver();
    if (!img.getGraphics().drawImage(icon.getImage(), 0, 0, width, height, background, observer)) {
        try {
            observer.waitForDone();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return new byte[0];
        }
    }
    IIOMetadata metadata = writer.getDefaultImageMetadata(new ImageTypeSpecifier(img),
            writer.getDefaultWriteParam());
    if (format.equalsIgnoreCase("jpg")) {
        Element tree = (Element) metadata.getAsTree("javax_imageio_jpeg_image_1.0");
        Element jfif = (Element) tree.getElementsByTagName("app0JFIF").item(0);
        jfif.setAttribute("Xdensity", Integer.toString(72));
        jfif.setAttribute("Ydensity", Integer.toString(72));
        jfif.setAttribute("resUnits", "1");
        metadata.setFromTree("javax_imageio_jpeg_image_1.0", tree);
    } else {
        double dotsPerMilli = 7.2 / 2.54;
        IIOMetadataNode horiz = new IIOMetadataNode("HorizontalPixelSize");
        horiz.setAttribute("value", Double.toString(dotsPerMilli));
        IIOMetadataNode vert = new IIOMetadataNode("VerticalPixelSize");
        vert.setAttribute("value", Double.toString(dotsPerMilli));
        IIOMetadataNode dim = new IIOMetadataNode("Dimension");
        dim.appendChild(horiz);
        dim.appendChild(vert);
        IIOMetadataNode root = new IIOMetadataNode("javax_imageio_1.0");
        root.appendChild(dim);
        metadata.mergeTree("javax_imageio_1.0", root);
    }

    writer.write(null, new IIOImage(img, null, metadata), null);
    return output.toByteArray();
}