Example usage for javax.imageio ImageWriter setOutput

List of usage examples for javax.imageio ImageWriter setOutput

Introduction

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

Prototype

public void setOutput(Object output) 

Source Link

Document

Sets the destination to the given ImageOutputStream or other Object .

Usage

From source file:FileUtils.java

/**
 * Utility method to write BufferedImage object to disk
 * @param image - BufferedImage object to save.
 * @param data - relative path to the image
 * @param format - file prefix of the image
 * @return BufferedImage representation of the image
 *
 *//*from   w  w  w.jav a 2  s.  co m*/
public static void imageToBitmap(BufferedImage image, String data, String format) throws IOException {
    final OutputStream inb = new FileOutputStream(data);
    final ImageWriter wrt = ImageIO.getImageWritersByFormatName(format).next();
    final ImageInputStream imageInput = ImageIO.createImageOutputStream(inb);
    wrt.setOutput(imageInput);
    wrt.write(image);
    inb.close();
}

From source file:ImageUtilities.java

/**
 * Writes an image to an output stream as a JPEG file. The JPEG quality can
 * be specified in percent./*from   ww w . ja va  2s  .  c  o  m*/
 * 
 * @param image
 *            image to be written
 * @param stream
 *            target stream
 * @param qualityPercent
 *            JPEG quality in percent
 * 
 * @throws IOException
 *             if an I/O error occured
 * @throws IllegalArgumentException
 *             if qualityPercent not between 0 and 100
 */
public static void saveImageAsJPEG(BufferedImage image, OutputStream stream, int qualityPercent)
        throws IOException {
    if ((qualityPercent < 0) || (qualityPercent > 100)) {
        throw new IllegalArgumentException("Quality out of bounds!");
    }
    float quality = qualityPercent / 100f;
    ImageWriter writer = null;
    Iterator iter = ImageIO.getImageWritersByFormatName("jpg");
    if (iter.hasNext()) {
        writer = (ImageWriter) iter.next();
    }
    ImageOutputStream ios = ImageIO.createImageOutputStream(stream);
    writer.setOutput(ios);
    ImageWriteParam iwparam = new JPEGImageWriteParam(Locale.getDefault());
    iwparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    iwparam.setCompressionQuality(quality);
    writer.write(null, new IIOImage(image, null, null), iwparam);
    ios.flush();
    writer.dispose();
    ios.close();
}

From source file:ImageUtils.java

/**
 * Compress and save an image to the disk. Currently this method only supports JPEG images.
 * // w w w.  j av a2 s  .  c om
 * @param image The image to save
 * @param toFileName The filename to use
 * @param type The image type. Use <code>ImageUtils.IMAGE_JPEG</code> to save as JPEG images,
 * or <code>ImageUtils.IMAGE_PNG</code> to save as PNG.
 */
public static void saveCompressedImage(BufferedImage image, String toFileName, int type) {
    try {
        if (type == IMAGE_PNG) {
            throw new UnsupportedOperationException("PNG compression not implemented");
        }

        Iterator iter = ImageIO.getImageWritersByFormatName("jpg");
        ImageWriter writer;
        writer = (ImageWriter) iter.next();

        ImageOutputStream ios = ImageIO.createImageOutputStream(new File(toFileName));
        writer.setOutput(ios);

        ImageWriteParam iwparam = new JPEGImageWriteParam(Locale.getDefault());

        iwparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        iwparam.setCompressionQuality(0.7F);

        writer.write(null, new IIOImage(image, null, null), iwparam);

        ios.flush();
        writer.dispose();
        ios.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.esxx.Response.java

public static void writeObject(Object object, ContentType ct, OutputStream out) throws IOException {

    if (object == null) {
        return;/*from w w  w  .  jav  a2 s  .c  o m*/
    }

    // Unwrap wrapped objects
    object = JS.toJavaObject(object);

    // Convert complex types to primitive types
    if (object instanceof Node) {
        ESXX esxx = ESXX.getInstance();

        if (ct.match("message/rfc822")) {
            try {
                String xml = esxx.serializeNode((Node) object);
                org.esxx.xmtp.XMTPParser xmtpp = new org.esxx.xmtp.XMTPParser();
                javax.mail.Message msg = xmtpp.convertMessage(new StringReader(xml));
                object = new ByteArrayOutputStream();
                msg.writeTo(new FilterOutputStream((OutputStream) object) {
                    @Override
                    public void write(int b) throws IOException {
                        if (b == '\r') {
                            return;
                        } else if (b == '\n') {
                            out.write('\r');
                            out.write('\n');
                        } else {
                            out.write(b);
                        }
                    }
                });
            } catch (javax.xml.stream.XMLStreamException ex) {
                throw new ESXXException("Failed to serialize Node as message/rfc822:" + ex.getMessage(), ex);
            } catch (javax.mail.MessagingException ex) {
                throw new ESXXException("Failed to serialize Node as message/rfc822:" + ex.getMessage(), ex);
            }
        } else {
            object = esxx.serializeNode((Node) object);
        }
    } else if (object instanceof Scriptable) {
        if (ct.match("application/x-www-form-urlencoded")) {
            String cs = Parsers.getParameter(ct, "charset", "UTF-8");

            object = StringUtil.encodeFormVariables(cs, (Scriptable) object);
        } else if (ct.match("text/csv")) {
            object = jsToCSV(ct, (Scriptable) object);
        } else {
            object = jsToJSON(object).toString();
        }
    } else if (object instanceof byte[]) {
        object = new ByteArrayInputStream((byte[]) object);
    } else if (object instanceof File) {
        object = new FileInputStream((File) object);
    }

    // Serialize primitive types
    if (object instanceof ByteArrayOutputStream) {
        ByteArrayOutputStream bos = (ByteArrayOutputStream) object;

        bos.writeTo(out);
    } else if (object instanceof ByteBuffer) {
        // Write result as-is to output stream
        WritableByteChannel wbc = Channels.newChannel(out);
        ByteBuffer bb = (ByteBuffer) object;

        bb.rewind();

        while (bb.hasRemaining()) {
            wbc.write(bb);
        }

        wbc.close();
    } else if (object instanceof InputStream) {
        IO.copyStream((InputStream) object, out);
    } else if (object instanceof Reader) {
        // Write stream as-is, using the specified charset (if present)
        String cs = Parsers.getParameter(ct, "charset", "UTF-8");
        Writer ow = new OutputStreamWriter(out, cs);

        IO.copyReader((Reader) object, ow);
    } else if (object instanceof String) {
        // Write string as-is, using the specified charset (if present)
        String cs = Parsers.getParameter(ct, "charset", "UTF-8");
        Writer ow = new OutputStreamWriter(out, cs);
        ow.write((String) object);
        ow.flush();
    } else if (object instanceof RenderedImage) {
        Iterator<ImageWriter> i = ImageIO.getImageWritersByMIMEType(ct.getBaseType());

        if (!i.hasNext()) {
            throw new ESXXException("No ImageWriter available for " + ct.getBaseType());
        }

        ImageWriter writer = i.next();

        writer.setOutput(ImageIO.createImageOutputStream(out));
        writer.write((RenderedImage) object);
    } else {
        throw new UnsupportedOperationException("Unsupported object class type: " + object.getClass());
    }
}

From source file:org.onehippo.forge.gallerymagick.core.command.ScalrProcessorUtils.java

/**
 * Creates and returns an {@link ImageWriter} instance from the {@code targetFile}.
 * @param targetFile target file/* w w  w .j  a  va2 s  . c o m*/
 * @return an {@link ImageWriter} instance
 * @throws IOException if IOException occurs
 */
private static ImageWriter getImageWriter(File targetFile) throws IOException {
    ImageWriter writer = null;
    String extension = FilenameUtils.getExtension(targetFile.getName());
    Iterator<ImageWriter> it = ImageIO.getImageWritersBySuffix(extension);

    if (it.hasNext()) {
        writer = it.next();
        ImageOutputStream output = new FileImageOutputStream(targetFile);
        writer.setOutput(output);
    }

    return writer;
}

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 .  ja va  2 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:common.utils.ImageUtils.java

public static void writeImage(BufferedImage image, float quality, OutputStream out) throws IOException {
    ImageWriter writer = getImageWriter();
    if (writer == null)
        return;//from w  w  w .j a v  a  2s  . c  o m
    ImageOutputStream ios = ImageIO.createImageOutputStream(out);
    writer.setOutput(ios);
    ImageWriteParam param = writer.getDefaultWriteParam();
    //JPEGImageWriteParam param = new JPEGImageWriteParam(Locale.getDefault());
    //param.setOptimizeHuffmanTables(true);
    if (quality >= 0) {
        param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        param.setCompressionQuality(quality);
        //param.setCompressionMode(ImageWriteParam.MODE_COPY_FROM_METADATA);
        //param.setProgressiveMode(ImageWriteParam.MODE_DISABLED);
        //param.setTilingMode(ImageWriteParam.MODE_DISABLED);
    }
    writer.write(null, new IIOImage(image, null, null), param);
}

From source file:editeurpanovisu.ReadWriteImage.java

/**
 *
 * @param img/*from  w ww.j  a  v  a  2 s  .c  om*/
 * @param destFile
 * @param sharpen
 * @param sharpenLevel
 * @throws IOException
 */
public static void writePng(Image img, String destFile, boolean sharpen, float sharpenLevel)
        throws IOException {
    sharpenMatrix = calculeSharpenMatrix(sharpenLevel);
    BufferedImage imageRGBSharpen = null;
    IIOImage iioImage = null;
    BufferedImage image = SwingFXUtils.fromFXImage(img, null); // Get buffered image.
    BufferedImage imageRGB = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.BITMASK);
    Graphics2D graphics = imageRGB.createGraphics();
    graphics.drawImage(image, 0, 0, null);
    if (sharpen) {
        imageRGBSharpen = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
        Kernel kernel = new Kernel(3, 3, sharpenMatrix);
        ConvolveOp cop = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
        cop.filter(imageRGB, imageRGBSharpen);
    }
    ImageWriter writer = null;
    FileImageOutputStream output = null;
    try {
        writer = ImageIO.getImageWritersByFormatName("png").next();
        ImageWriteParam param = writer.getDefaultWriteParam();
        output = new FileImageOutputStream(new File(destFile));
        writer.setOutput(output);
        if (sharpen) {
            iioImage = new IIOImage(imageRGBSharpen, null, null);
        } else {
            iioImage = new IIOImage(imageRGB, null, null);
        }
        writer.write(null, iioImage, param);
    } catch (IOException ex) {
        throw ex;
    } finally {
        if (writer != null) {
            writer.dispose();
        }
        if (output != null) {
            output.close();
        }
    }
    graphics.dispose();
}

From source file:editeurpanovisu.ReadWriteImage.java

/**
 *
 * @param img/* w  w  w  .  ja  va2  s  . co  m*/
 * @param destFile
 * @param sharpen
 * @param sharpenLevel
 * @throws IOException
 */
public static void writeBMP(Image img, String destFile, boolean sharpen, float sharpenLevel)
        throws IOException {
    sharpenMatrix = calculeSharpenMatrix(sharpenLevel);
    BufferedImage imageRGBSharpen = null;
    IIOImage iioImage = null;

    BufferedImage image = SwingFXUtils.fromFXImage(img, null); // Get buffered image.
    BufferedImage imageRGB = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.OPAQUE); // Remove alpha-channel from buffered image.

    Graphics2D graphics = imageRGB.createGraphics();
    graphics.drawImage(image, 0, 0, null);
    if (sharpen) {

        imageRGBSharpen = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
        Kernel kernel = new Kernel(3, 3, sharpenMatrix);
        ConvolveOp cop = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
        cop.filter(imageRGB, imageRGBSharpen);
    }
    ImageWriter writer = null;
    FileImageOutputStream output = null;
    try {
        writer = ImageIO.getImageWritersByFormatName("bmp").next();
        ImageWriteParam param = writer.getDefaultWriteParam();
        output = new FileImageOutputStream(new File(destFile));
        writer.setOutput(output);
        if (sharpen) {
            iioImage = new IIOImage(imageRGBSharpen, null, null);
        } else {
            iioImage = new IIOImage(imageRGB, null, null);
        }
        writer.write(null, iioImage, param);
    } catch (IOException ex) {
        throw ex;
    } finally {
        if (writer != null) {
            writer.dispose();
        }
        if (output != null) {
            output.close();
        }
    }
    graphics.dispose();
}

From source file:org.apache.axis2.jaxws.marshaller.impl.alt.Attachment.java

private static byte[] createBytesFromImage(Image image, String mimeType) {
    try {//www. j  a  v a 2  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);
    }

}