Example usage for javax.imageio.stream ImageOutputStream close

List of usage examples for javax.imageio.stream ImageOutputStream close

Introduction

In this page you can find the example usage for javax.imageio.stream ImageOutputStream close.

Prototype

void close() throws IOException;

Source Link

Document

Closes the stream.

Usage

From source file:org.geowebcache.layer.MetaTile.java

/**
 * Outputs one tile from the internal array of tiles to a provided stream
 * /*from w  w w. j a  v a  2  s. com*/
 * @param tileIdx
 *            the index of the tile relative to the internal array
 * @param format
 *            the Java name for the format
 * @param resource
 *            the outputstream
 * @return true if no error was encountered
 * @throws IOException
 */
public boolean writeTileToStream(final int tileIdx, Resource target) throws IOException {
    if (tiles == null) {
        return false;
    }
    String format = responseFormat.getInternalName();

    if (log.isDebugEnabled()) {
        log.debug("Thread: " + Thread.currentThread().getName() + " writing: " + tileIdx);
    }

    // TODO should we recycle the writers ?
    // GR: it'd be only a 2% perf gain according to profile   
    Iterator<ImageWriter> it = javax.imageio.ImageIO.getImageWritersByFormatName(format);
    ImageWriter writer = it.next();
    ImageWriteParam param = writer.getDefaultWriteParam();

    if (this.formatModifier != null) {
        param = formatModifier.adjustImageWriteParam(param);
    }

    Rectangle tileRegion = tiles[tileIdx];
    RenderedImage tile = createTile(tileRegion.x, tileRegion.y, tileRegion.width, tileRegion.height);
    disposeLater(tile);
    OutputStream outputStream = target.getOutputStream();
    ImageOutputStream imgOut = new MemoryCacheImageOutputStream(outputStream);
    writer.setOutput(imgOut);
    IIOImage image = new IIOImage(tile, null, null);
    try {
        writer.write(null, image, param);
    } finally {
        imgOut.close();
        writer.dispose();
    }

    return true;
}

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>/*from   ww  w.j ava 2 s .  co 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 ww .j  a  v a  2 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./* w  ww .j a va  2s  . c  o  m*/
 *
 * @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.jahia.services.image.AbstractJava2DImageService.java

protected void saveImageToFile(BufferedImage dest, String mimeType, File destFile) throws IOException {
    Iterator<ImageWriter> suffixWriters = ImageIO.getImageWritersByMIMEType(mimeType);
    if (suffixWriters.hasNext()) {
        ImageWriter imageWriter = suffixWriters.next();
        ImageOutputStream imageOutputStream = new FileImageOutputStream(destFile);
        imageWriter.setOutput(imageOutputStream);
        imageWriter.write(dest);//from ww  w  .  jav  a 2 s.  co m
        imageOutputStream.close();
    } else {
        logger.warn(
                "Couldn't find a writer for mime type : " + mimeType + "(" + this.getClass().getName() + ")");
    }
}

From source file:org.modelibra.util.ImageHandler.java

/**
 * Saves an image to a jpeg file.//from   www.j  av a2 s . c  o  m
 * 
 * @param bi
 *            buffered image
 * @param file
 *            jpeg file
 * @param quality
 *            image quality
 */
public static void saveImageToJPEGFile14(BufferedImage bi, File file, float quality) throws IOException {

    JPEGImageWriteParam param = new JPEGImageWriteParam(null);
    ImageTypeSpecifier type = new ImageTypeSpecifier(bi);
    param.setDestinationType(type);
    ImageOutputStream imgos = ImageIO.createImageOutputStream(file);
    Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpeg");
    ImageWriter writer = writers.next();
    writer.setOutput(imgos);
    writer.write(bi);
    imgos.close();
}

From source file:org.mrgeo.services.ServletUtils.java

/**
 * Writes an image to a servlet response
 * @param response servlet response/*from w w w. j  ava 2  s  .  co  m*/
 * @param image image bytes
 * @throws IOException
 */
public static void writeImageToResponse(HttpServletResponse response, byte[] image) throws IOException {
    try {
        ImageOutputStream imageStream = new MemoryCacheImageOutputStream(response.getOutputStream());
        imageStream.write(image, 0, image.length);
        response.setContentLength((int) imageStream.length());
        imageStream.close();
    }
    // TODO: remove these catches - This is to prevent seeing the broken pipes exception
    // over and over again in the trace...leave catch in until issue is fixed (#1122)
    catch (IIOException e) {
    } catch (IndexOutOfBoundsException e) {
    }
}

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  . j  a v  a2 s . com*/
 * @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/* ww  w  .  ja  v a2s. c o  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.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 www. j a v  a 2  s.  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");
}