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:Main.java

public static void main(String[] args) throws Exception {
    URL url = new URL("http://www.java2s.com/style/download.png");
    BufferedImage bi = ImageIO.read(url);
    for (float q = 0.2f; q < .9f; q += .2f) {
        OutputStream outStream = new FileOutputStream(new File("c:/Java_Dev/Image-" + q + ".jpg"));
        ImageWriter imgWriter = ImageIO.getImageWritersByFormatName("jpg").next();
        ImageOutputStream ioStream = ImageIO.createImageOutputStream(outStream);
        imgWriter.setOutput(ioStream);//from   w w  w  . ja v a 2  s .  co m

        JPEGImageWriteParam jpegParams = new JPEGImageWriteParam(Locale.getDefault());
        jpegParams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        jpegParams.setCompressionQuality(q);

        imgWriter.write(null, new IIOImage(bi, null, null), jpegParams);

        ioStream.flush();
        ioStream.close();
        imgWriter.dispose();
    }
}

From source file:Main.java

private static void writeJpegCompressedImage(BufferedImage image, String outFile) throws IOException {
    float qualityFloat = 1f;
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();

    ImageWriter imgWriter = ImageIO.getImageWritersByFormatName("jpg").next();
    ImageOutputStream ioStream = ImageIO.createImageOutputStream(outStream);
    imgWriter.setOutput(ioStream);/*from  w  w  w  .java  2s  .  com*/

    JPEGImageWriteParam jpegParams = new JPEGImageWriteParam(Locale.getDefault());
    jpegParams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    jpegParams.setCompressionQuality(qualityFloat);

    imgWriter.write(null, new IIOImage(image, null, null), jpegParams);

    ioStream.flush();
    ioStream.close();
    imgWriter.dispose();

    OutputStream outputStream = new FileOutputStream(outFile);
    outStream.writeTo(outputStream);

}

From source file:de.bamamoto.mactools.png2icns.Scaler.java

public static void save(BufferedImage image, String filename) throws IOException {
    Iterator writers = ImageIO.getImageWritersByFormatName("PNG");
    if (writers.hasNext()) {
        ImageWriter imageWriter = (ImageWriter) writers.next();
        ImageWriteParam params = imageWriter.getDefaultWriteParam();

        File outFile = new File(filename);
        try (FileImageOutputStream output = new FileImageOutputStream(outFile)) {
            imageWriter.setOutput(output);
            IIOImage outImage = new IIOImage(image, null, null);
            imageWriter.write(null, outImage, params);
        }/*from  ww w . ja  v a2  s.  c  o m*/
    }
}

From source file:ImageUtilities.java

/**
 * Writes an image to an output stream as a JPEG file. The JPEG quality can
 * be specified in percent.//ww w  .  j  a va 2  s. 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:org.egov.infra.utils.ImageUtils.java

public static File compressImage(final InputStream imageStream, String imageFileName, boolean closeStream)
        throws IOException {
    File compressedImage = Paths.get(imageFileName).toFile();
    try (final ImageOutputStream imageOutput = createImageOutputStream(compressedImage)) {
        ImageWriter writer = getImageWritersByFormatName(
                defaultString(getExtension(imageFileName), JPG_FORMAT_NAME)).next();
        writer.setOutput(imageOutput);//from w  w w  .java  2  s  .c om
        ImageWriteParam writeParam = writer.getDefaultWriteParam();
        if (writeParam.canWriteCompressed()) {
            writeParam.setCompressionMode(MODE_EXPLICIT);
            writeParam.setCompressionType(writeParam.getCompressionTypes()[0]);
            writeParam.setCompressionQuality(0.05F);
        }
        writer.write(null, new IIOImage(read(imageStream), null, null), writeParam);
        writer.dispose();
        if (closeStream)
            imageStream.close();
    }
    return compressedImage;
}

From source file:ImageUtils.java

/**
 * Compress and save an image to the disk. Currently this method only supports JPEG images.
 * //from  w  ww  .j  ava 2s  .co  m
 * @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:com.mirth.connect.server.util.DICOMUtil.java

private static byte[] saveAsJpeg(ImagePlus imagePlug, int quality) {
    int imageType = BufferedImage.TYPE_INT_RGB;

    if (imagePlug.getProcessor().isDefaultLut()) {
        imageType = BufferedImage.TYPE_BYTE_GRAY;
    }//from  w w  w  .  ja va  2 s.  c o m

    BufferedImage bufferedImage = new BufferedImage(imagePlug.getWidth(), imagePlug.getHeight(), imageType);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    try {
        Graphics graphics = bufferedImage.createGraphics();
        graphics.drawImage(imagePlug.getImage(), 0, 0, null);
        graphics.dispose();
        ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next();
        writer.setOutput(ImageIO.createImageOutputStream(baos));
        ImageWriteParam param = writer.getDefaultWriteParam();
        param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        param.setCompressionQuality(quality / 100f);

        if (quality == 100) {
            param.setSourceSubsampling(1, 1, 0, 0);
        }

        IIOImage iioImage = new IIOImage(bufferedImage, null, null);
        writer.write(null, iioImage, param);
        return baos.toByteArray();
    } catch (Exception e) {
        logger.error("Error converting dcm file", e);
    } finally {
        IOUtils.closeQuietly(baos);
    }

    return null;
}

From source file:com.mirth.connect.server.util.DICOMMessageUtil.java

private static byte[] saveAsJpeg(ImagePlus imagePlug, int quality) {
    int imageType = BufferedImage.TYPE_INT_RGB;

    if (imagePlug.getProcessor().isDefaultLut()) {
        imageType = BufferedImage.TYPE_BYTE_GRAY;
    }/* w w w.  j  a  va2s.  co  m*/

    BufferedImage bufferedImage = new BufferedImage(imagePlug.getWidth(), imagePlug.getHeight(), imageType);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    try {
        Graphics graphics = bufferedImage.createGraphics();
        graphics.drawImage(imagePlug.getImage(), 0, 0, null);
        graphics.dispose();
        ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next();
        writer.setOutput(ImageIO.createImageOutputStream(baos));
        ImageWriteParam param = writer.getDefaultWriteParam();
        param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        param.setCompressionQuality(quality / 100f);

        if (quality == 100) {
            param.setSourceSubsampling(1, 1, 0, 0);
        }

        IIOImage iioImage = new IIOImage(bufferedImage, null, null);
        writer.write(null, iioImage, param);
        return baos.toByteArray();
    } catch (Exception e) {
        logger.error("Error Converting DICOM image", e);
    } finally {
        IOUtils.closeQuietly(baos);
    }

    return null;
}

From source file:ch.rasc.downloadchart.DownloadChartServlet.java

private static void handleJpg(HttpServletResponse response, byte[] imageData, Integer width, Integer height,
        String filename, JpegOptions options) throws IOException {

    response.setContentType("image/jpeg");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + ".jpg\";");

    BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageData));

    Dimension newDimension = calculateDimension(image, width, height);
    int imgWidth = image.getWidth();
    int imgHeight = image.getHeight();
    if (newDimension != null) {
        imgWidth = newDimension.width;/*w  w w.jav  a2 s  . c om*/
        imgHeight = newDimension.height;
    }

    BufferedImage newImage = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB);

    Graphics2D g = newImage.createGraphics();
    g.drawImage(image, 0, 0, imgWidth, imgHeight, Color.BLACK, null);
    g.dispose();

    if (newDimension != null) {
        g.setComposite(AlphaComposite.Src);
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    }

    try (ImageOutputStream ios = ImageIO.createImageOutputStream(response.getOutputStream())) {
        Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpg");
        ImageWriter writer = iter.next();
        ImageWriteParam iwp = writer.getDefaultWriteParam();
        iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        if (options != null && options.quality != null && options.quality != 0 && options.quality != 100) {
            iwp.setCompressionQuality(options.quality / 100f);
        } else {
            iwp.setCompressionQuality(1);
        }
        writer.setOutput(ios);
        writer.write(null, new IIOImage(newImage, null, null), iwp);
        writer.dispose();
    }
}

From source file:ImageUtil.java

/**
 * store BufferedImage to file/*from w w  w . j av a  2 s .c o m*/
 * @param image BufferedImage
 * @param outputFile output image file
 * @param quality quality of output image
 * @return true success, else fail
 */
public static boolean storeImage(BufferedImage image, File outputFile, float quality) {
    try {
        //reconstruct folder structure for image file output
        if (outputFile.getParentFile() != null && !outputFile.getParentFile().exists()) {
            outputFile.getParentFile().mkdirs();
        }
        if (outputFile.exists()) {
            outputFile.delete();
        }
        //get image file suffix
        String extName = "png";
        //get registry ImageWriter for specified image suffix
        Iterator writers = ImageIO.getImageWritersByFormatName(extName);
        ImageWriter imageWriter = (ImageWriter) writers.next();
        //set image output params
        ImageWriteParam params = new JPEGImageWriteParam(null);
        params.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        params.setCompressionQuality(quality);
        params.setProgressiveMode(javax.imageio.ImageWriteParam.MODE_DISABLED);
        params.setDestinationType(new ImageTypeSpecifier(IndexColorModel.getRGBdefault(),
                IndexColorModel.getRGBdefault().createCompatibleSampleModel(16, 16)));
        //writer image to file
        ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(outputFile);
        imageWriter.setOutput(imageOutputStream);
        imageWriter.write(null, new IIOImage(image, null, null), params);
        imageOutputStream.close();
        imageWriter.dispose();
        return true;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}