Example usage for javax.imageio ImageWriteParam MODE_EXPLICIT

List of usage examples for javax.imageio ImageWriteParam MODE_EXPLICIT

Introduction

In this page you can find the example usage for javax.imageio ImageWriteParam MODE_EXPLICIT.

Prototype

int MODE_EXPLICIT

To view the source code for javax.imageio ImageWriteParam MODE_EXPLICIT.

Click Source Link

Document

A constant value that may be passed into methods such as setTilingMode or setCompressionMode to enable a feature for future writes.

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);/*  w w w .  j  a va2s . c  om*/

        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  .j  av  a  2 s.  co  m

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

/**
 * store BufferedImage to file/*ww w  .j  av a  2 s  .c  om*/
 * @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;
}

From source file:gr.iti.mklab.reveal.forensics.util.Util.java

public static BufferedImage recompressImage(BufferedImage imageIn, int quality) {
    // Apply in-memory JPEG compression to a BufferedImage given a quality setting (0-100)
    // and return the resulting BufferedImage
    float fQuality = (float) (quality / 100.0);
    BufferedImage outputImage = null;
    try {//  www  . j av a  2 s.  c  om
        ImageWriter writer;
        Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpeg");
        writer = iter.next();
        ImageWriteParam iwp = writer.getDefaultWriteParam();
        iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        iwp.setCompressionQuality(fQuality);
        byte[] imageInByte;
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            MemoryCacheImageOutputStream mcios = new MemoryCacheImageOutputStream(baos);
            writer.setOutput(mcios);
            IIOImage tmpImage = new IIOImage(imageIn, null, null);
            writer.write(null, tmpImage, iwp);
            writer.dispose();
            baos.flush();
            imageInByte = baos.toByteArray();
        }
        InputStream in = new ByteArrayInputStream(imageInByte);
        outputImage = ImageIO.read(in);
    } catch (Exception ex) {
        Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex);
    }
    return outputImage;
}

From source file:com.oneis.utils.ImageColouring.java

/**
 * Transform the colours in an image.//from w w w  . j a  v  a2 s .  c  o m
 *
 * @param Filename Full pathname to the source file
 * @param Method Which colouring method to use, use METHOD_* constants
 * @param Colours Array of 0xRRGGBB colours for recolouring
 * @param JPEGQuality If the image is a JPEG, the output quality for
 * reencoding
 * @param Output An OutputStream to write the file. Will be closed.
 */
static public void colourImage(String Filename, int Method, int[] Colours, int JPEGQuality, OutputStream Output)
        throws IOException {
    ColouringInfo colouringInfo = prepareForColouring(Method, Colours);

    String extension = Filename.substring(Filename.lastIndexOf('.') + 1, Filename.length());
    String outputFormat = extension;

    if (outputFormat.equals("gif")) {
        if (!colourImageGIF(Filename, colouringInfo, Output)) {
            throw new RuntimeException("Failed to directly colour GIF file");
        }
        return;
    }

    BufferedImage image = ImageIO.read(new File(Filename));
    int width = image.getWidth();
    int height = image.getHeight();

    // Rewrite the pixels
    int[] pixelBuffer = new int[width];
    for (int y = 0; y < height; ++y) {
        image.getRGB(0, y, width, 1, pixelBuffer, 0, width);
        doColouring(pixelBuffer, colouringInfo);
        image.setRGB(0, y, width, 1, pixelBuffer, 0, width);
    }

    // Writing is done the hard way to enable the JPEG quality to be set.
    // Get a writer
    Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName(outputFormat);
    if (!iter.hasNext()) {
        throw new RuntimeException("Couldn't write image of type " + outputFormat);
    }

    ImageWriter writer = iter.next();

    ImageWriteParam iwparam = null;

    // Is it JPEG? If so, might want to set the quality
    if (outputFormat.equals("jpeg") || outputFormat.equals("jpg")) {
        // Clamp value
        int q = JPEGQuality;
        if (q < 10) {
            q = 10;
        }
        if (q > 100) {
            q = 100;
        }

        JPEGImageWriteParam jparam = new JPEGImageWriteParam(null);
        jparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        jparam.setCompressionQuality((float) (((float) q) / 100.0));
        iwparam = jparam;
    }

    ImageOutputStream output = ImageIO.createImageOutputStream(Output);
    writer.setOutput(output);
    writer.write(null, new IIOImage(image, null, null), iwparam);

    output.close();
}

From source file:doge.photo.DogePhotoManipulator.java

@Override
public Photo manipulate(Photo photo) throws IOException {
    BufferedImage sourceImage = readImage(photo);
    BufferedImage destinationImage = manipulate(sourceImage);
    Photo resultPhoto = () -> {/*from  w ww.  ja v  a 2s. c o  m*/
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageOutputStream ios = ImageIO.createImageOutputStream(outputStream);
        ImageWriter writer = ImageIO.getImageWritersByFormatName("jpeg").next();
        ImageWriteParam param = writer.getDefaultWriteParam();
        param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        param.setCompressionQuality(0.85f);
        writer.setOutput(ios);
        writer.write(null, new IIOImage(destinationImage, null, null), param);
        ImageIO.write(destinationImage, "jpeg", outputStream);
        return new ByteArrayInputStream(outputStream.toByteArray());
    };
    return resultPhoto;
}

From source file:mobac.program.tiledatawriter.TileImageJpegDataWriter.java

public void initialize() {
    if (log.isTraceEnabled()) {
        String s = "Available JPEG image writers:";
        Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpeg");
        while (writers.hasNext()) {
            ImageWriter w = writers.next();
            s += "\n\t" + w.getClass().getName();
        }// ww w . j  ava 2 s .c om
        log.trace(s);
    }
    jpegImageWriter = ImageIO.getImageWritersByFormatName("jpeg").next();
    if (jpegImageWriter == null)
        throw new NullPointerException("Unable to create a JPEG image writer");
    jpegImageWriter.addIIOWriteWarningListener(ImageWriterWarningListener.INSTANCE);
    log.debug("Used JPEG image writer: " + jpegImageWriter.getClass().getName());
    iwp = jpegImageWriter.getDefaultWriteParam();
    iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    iwp.setCompressionQuality(jpegCompressionLevel);
}

From source file:ImageUtilities.java

/**
 * Writes an image to an output stream as a JPEG file. The JPEG quality can
 * be specified in percent./*w w  w  . j  av a2s.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:ScreenCapture.java

private void save() {
    if (ia.getImage() == null) {
        System.out.println("No captured image.");
        return;//from w  ww .ja  va 2s . c  o m
    }
    ImageWriter writer = null;
    ImageOutputStream ios = null;

    try {
        Iterator iter = ImageIO.getImageWritersByFormatName("jpeg");

        if (!iter.hasNext()) {
            System.out.println("Unable to save image to jpeg file type.");
            return;
        }
        writer = (ImageWriter) iter.next();
        ios = ImageIO.createImageOutputStream(new File("c:\\a.jpg"));
        writer.setOutput(ios);
        ImageWriteParam iwp = writer.getDefaultWriteParam();
        iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        iwp.setCompressionQuality(0.95f);
        writer.write(null, new IIOImage((BufferedImage) ia.getImage(), null, null), iwp);
    } catch (Exception e2) {
        e2.printStackTrace();
    }

}

From source file:ar.com.zauber.common.image.impl.AbstractImage.java

/**
 * Creates a thumbnail//w w  w .  j a va2s  .  c o  m
 * 
 * @param is data source
 * @param os data source
 * @throws IOException if there is a problem reading is
 */
public static void createThumbnail(final InputStream is, final OutputStream os, final int target)
        throws IOException {
    final float compression = 0.85F;
    ImageWriter writer = null;
    MemoryCacheImageOutputStream mos = null;
    Graphics2D graphics2D = null;
    try {
        final BufferedImage bi = ImageIO.read(is);
        final Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("JPG");
        if (!iter.hasNext()) {
            throw new IllegalStateException("can't find JPG subsystem");
        }

        int w = bi.getWidth(), h = bi.getHeight();
        if (w < target && h < target) {
            // nothing to recalculate, ya es chiquita.
        } else {
            if (w > h) {
                h = target * bi.getHeight() / bi.getWidth();
                w = target;
            } else {
                w = target * bi.getWidth() / bi.getHeight();
                h = target;
            }
        }
        // draw original image to thumbnail image object and
        // scale it to the new size on-the-fly
        final BufferedImage thumbImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        graphics2D = thumbImage.createGraphics();
        graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        graphics2D.drawImage(bi, 0, 0, w, h, null);

        writer = (ImageWriter) iter.next();
        final ImageWriteParam iwp = writer.getDefaultWriteParam();
        iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        iwp.setCompressionQuality(compression);
        mos = new MemoryCacheImageOutputStream(os);
        writer.setOutput(mos);
        writer.write(null, new IIOImage(thumbImage, null, null), iwp);
    } finally {
        if (writer != null) {
            writer.dispose();
        }
        if (mos != null) {
            mos.close();
        }
        if (graphics2D != null) {
            graphics2D.dispose();
        }
        is.close();
        os.close();
    }
}