Example usage for javax.imageio IIOImage IIOImage

List of usage examples for javax.imageio IIOImage IIOImage

Introduction

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

Prototype

public IIOImage(Raster raster, List<? extends BufferedImage> thumbnails, IIOMetadata metadata) 

Source Link

Document

Constructs an IIOImage containing a Raster , and thumbnails and metadata associated with it.

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  v  a 2  s .  com*/

        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);// w  w  w . ja  v a2s .  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//from w ww.j  a v  a 2s  . 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;
}

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 {/*from  w w w. j av  a 2 s  .  c  o  m*/
        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:io.warp10.script.processing.Pencode.java

@Override
public Object apply(WarpScriptStack stack) throws WarpScriptException {
    Object top = stack.pop();//from   w  w  w  .  ja  v  a  2 s.  co m

    if (!(top instanceof processing.core.PGraphics)) {
        throw new WarpScriptException(getName() + " operates on a PGraphics instance.");
    }

    processing.core.PGraphics pg = (processing.core.PGraphics) top;

    pg.endDraw();

    BufferedImage bimage = new BufferedImage(pg.pixelWidth, pg.pixelHeight, BufferedImage.TYPE_INT_ARGB);
    bimage.setRGB(0, 0, pg.pixelWidth, pg.pixelHeight, pg.pixels, 0, pg.pixelWidth);
    Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("png");
    ImageWriter writer = null;
    if (iter.hasNext()) {
        writer = iter.next();
    }
    ImageWriteParam param = writer.getDefaultWriteParam();
    IIOMetadata metadata = null;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    BufferedOutputStream output = new BufferedOutputStream(baos);

    try {
        writer.setOutput(ImageIO.createImageOutputStream(output));
        writer.write(metadata, new IIOImage(bimage, null, metadata), param);
    } catch (IOException ioe) {
        throw new WarpScriptException(getName() + " error while encoding PGraphics.", ioe);
    }

    writer.dispose();

    StringBuilder sb = new StringBuilder("data:image/png;base64,");
    sb.append(Base64.encodeBase64String(baos.toByteArray()));

    stack.push(sb.toString());

    //
    // Re-issue a 'beginDraw' so we can continue using the PGraphics instance
    //

    pg.beginDraw();

    return stack;
}

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 = () -> {/*w  ww. j a  va2 s. c om*/
        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:com.oneis.utils.ImageColouring.java

/**
 * Transform the colours in an image./*from  w  w  w . j  av a2  s .co 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:com.actelion.research.orbit.imageAnalysis.utils.ImageUtils.java

/**
 * Stores BufferedImage as JPEG2000 encoded file.
 *
 * @param bi//from   w w w. j av  a  2  s  .c  o m
 * @param filename
 * @param dEncRate
 * @param lossless
 * @throws IOException
 */
public static void storeBIAsJP2File(BufferedImage bi, String filename, double dEncRate, boolean lossless)
        throws IOException {

    if (hasJPEG2000FileTag(filename)) {

        IIOImage iioImage = new IIOImage(bi, null, null);

        ImageWriter jp2iw = ImageIO.getImageWritersBySuffix("jp2").next();
        J2KImageWriteParam writeParam = (J2KImageWriteParam) jp2iw.getDefaultWriteParam();

        // Indicates using the lossless scheme or not. It is equivalent to use reversible quantization and 5x3 integer wavelet filters. The default is true.
        writeParam.setLossless(lossless);

        if (lossless)
            writeParam.setFilter(J2KImageWriteParam.FILTER_53); // Specifies which wavelet filters to use for the specified tile-components. JPEG 2000 part I only supports w5x3 and w9x7 filters.
        else
            writeParam.setFilter(J2KImageWriteParam.FILTER_97);

        if (!lossless) {
            // The bitrate in bits-per-pixel for encoding. Should be set when lossy compression scheme is used. With the default value Double.MAX_VALUE, a lossless compression will be done.
            writeParam.setEncodingRate(dEncRate);

            // changes in compression rate are done in the following way
            // however JPEG2000 implementation seems not to support this <-- no differences visible
            //                writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            //                writeParam.setCompressionType(writeParam.getCompressionTypes()[0]);
            //                writeParam.setCompressionQuality(1.0f);
        }

        ImageOutputStream ios = null;
        try {
            ios = new FileImageOutputStream(new File(filename));
            jp2iw.setOutput(ios);
            jp2iw.write(null, iioImage, writeParam);
            jp2iw.dispose();
            ios.flush();
        } finally {
            if (ios != null)
                ios.close();
        }
    } else
        System.err.println("please name your file as valid JPEG2000 file: ends with .jp2");
}

From source file:net.d53dev.dslfy.web.service.GifService.java

public void saveAnimatedGIF(OutputStream out, List<GifFrame> frames, int loopCount) throws Exception {
    ImageWriter iw = ImageIO.getImageWritersByFormatName("gif").next();

    ImageOutputStream ios = ImageIO.createImageOutputStream(out);
    iw.setOutput(ios);//ww  w. j  a v  a 2s .c  o  m
    iw.prepareWriteSequence(null);

    int p = 0;
    for (GifFrame frame : frames) {
        ImageWriteParam iwp = iw.getDefaultWriteParam();
        IIOMetadata metadata = iw.getDefaultImageMetadata(new ImageTypeSpecifier(frame.img), iwp);
        this.configureGIFFrame(metadata, String.valueOf(frame.delay / 10L), p++, frame.disposalMethod,
                loopCount);
        IIOImage ii = new IIOImage(frame.img, null, metadata);
        iw.writeToSequence(ii, null);
    }

    iw.endWriteSequence();
    ios.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  w w w  . j  a v  a  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();
}