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:de.unigoettingen.sub.commons.contentlib.imagelib.JpegInterpreter.java

/************************************************************************************
 * Write the renderedimage to an {@link OutputStream}
 * //from w w w  .  j  a  v a  2s. co  m
 * @param outStream the {@link OutputStream} to write to
 ************************************************************************************/
@Override
public void writeToStream(FileOutputStream fos, OutputStream outStream) {
    if (this.renderedimage == null) { // no image available
        return;
    }
    try {
        // create a buffered Image, which has no Alpha channel
        // as JPEG does not support Alpha Channels and the
        // ImageIO doesn't care - but will create a corrupt JPEG
        BufferedImage noAlphaBi = ImageManipulator.fromRenderedToBufferedNoAlpha(renderedimage);
        ImageOutputStream imageOutStream = ImageIO.createImageOutputStream(outStream);

        // Iterator<ImageWriter> writerIter = ImageIO
        // .getImageWritersByFormatName("jpg");
        // ImageWriter writer = writerIter.next(); // get writer from ImageIO
        ImageWriter writer = new JPEGImageWriter(new JPEGImageWriterSpi());

        // create metadata by creating an XML tree
        ImageWriteParam writerParam = writer.getDefaultWriteParam();
        ImageTypeSpecifier its = new ImageTypeSpecifier(noAlphaBi);

        // ImageTypeSpecifier its = new
        // ImageTypeSpecifier(image.getColorModel(),
        // image.getSampleModel());

        // IIOMetadata iomd = writer.getDefaultImageMetadata(new
        // ImageTypeSpecifier(image), writerParam);
        // Element tree =
        // (Element)iomd.getAsTree("javax_imageio_jpeg_image_1.0");
        // Element tree = (Element)iomd.getAsTree("javax_imageio_1.0");
        //
        IIOMetadata iomd = writer.getDefaultImageMetadata(its, writerParam);

        // create the XML tree and modify the appropriate DOM elements
        // to set the metadata
        setMetadata(iomd);

        // set compression
        writerParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        float comprvalue = ((float) writerCompressionValue) / 100;
        writerParam.setCompressionQuality(comprvalue);

        // set output
        writer.setOutput(imageOutStream);
        writer.prepareWriteSequence(null);

        // create new image parameters to set the compression
        // Locale locale = new Locale("en");
        // JPEGImageWriteParam jpegWriteParam = new
        // JPEGImageWriteParam(locale);

        // IIOImage iioImage = new IIOImage(renderedimage, null, iomd);

        IIOImage iioImage = new IIOImage(noAlphaBi, null, iomd);
        writer.write(null, iioImage, writerParam);
        writer.endWriteSequence();
        imageOutStream.flush();

        if (fos != null) {
            ImageOutputStream imageToFile = ImageIO.createImageOutputStream(fos);
            writer.setOutput(imageToFile);
            writer.prepareWriteSequence(null);
            writer.write(null, iioImage, writerParam);
            writer.endWriteSequence();
            imageToFile.flush();
            imageToFile.close();
            fos.flush();
            fos.close();
        }

        // ByteArrayOutputStream baos = new ByteArrayOutputStream();

        // byte [] data = wi.getImageAsByteArray();

        writer.dispose();
        imageOutStream.close();

    } catch (IOException e) {
        LOGGER.error("IOException occured", e);
    }
}

From source file:com.itextpdf.text.pdf.pdfcleanup.PdfCleanUpRenderListener.java

private byte[] getJPGBytes(BufferedImage image) {
    ByteArrayOutputStream outputStream = null;

    try {//from   www .  j  ava  2s .  c  o  m
        ImageWriter jpgWriter = ImageIO.getImageWritersByFormatName("jpg").next();
        ImageWriteParam jpgWriteParam = jpgWriter.getDefaultWriteParam();
        jpgWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        jpgWriteParam.setCompressionQuality(1.0f);

        outputStream = new ByteArrayOutputStream();
        jpgWriter.setOutput(new MemoryCacheImageOutputStream((outputStream)));
        IIOImage outputImage = new IIOImage(image, null, null);

        jpgWriter.write(null, outputImage, jpgWriteParam);
        jpgWriter.dispose();
        outputStream.flush();

        return outputStream.toByteArray();
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        closeOutputStream(outputStream);
    }
}

From source file:de.unigoettingen.sub.commons.contentlib.imagelib.JpegInterpreter.java

@Override
public byte[] writeToStreamAndByteArray(OutputStream outStream) {
    byte[] data = null;
    if (this.renderedimage == null) { // no image available
        return data;
    }//from  w  ww  . ja  va2  s.  co m
    try {
        // create a buffered Image, which has no Alpha channel
        // as JPEG does not support Alpha Channels and the
        // ImageIO doesn't care - but will create a corrupt JPEG
        BufferedImage noAlphaBi = ImageManipulator.fromRenderedToBufferedNoAlpha(renderedimage);
        ImageOutputStream imageOutStream = ImageIO.createImageOutputStream(outStream);

        // Iterator<ImageWriter> writerIter = ImageIO
        // .getImageWritersByFormatName("jpg");
        // ImageWriter writer = writerIter.next(); // get writer from ImageIO
        ImageWriter writer = new JPEGImageWriter(new JPEGImageWriterSpi());

        // create metadata by creating an XML tree
        ImageWriteParam writerParam = writer.getDefaultWriteParam();
        ImageTypeSpecifier its = new ImageTypeSpecifier(noAlphaBi);

        // ImageTypeSpecifier its = new
        // ImageTypeSpecifier(image.getColorModel(),
        // image.getSampleModel());

        // IIOMetadata iomd = writer.getDefaultImageMetadata(new
        // ImageTypeSpecifier(image), writerParam);
        // Element tree =
        // (Element)iomd.getAsTree("javax_imageio_jpeg_image_1.0");
        // Element tree = (Element)iomd.getAsTree("javax_imageio_1.0");
        //
        IIOMetadata iomd = writer.getDefaultImageMetadata(its, writerParam);

        // create the XML tree and modify the appropriate DOM elements
        // to set the metadata
        setMetadata(iomd);

        // set compression
        writerParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        float comprvalue = ((float) writerCompressionValue) / 100;
        writerParam.setCompressionQuality(comprvalue);

        // set output
        writer.setOutput(imageOutStream);
        writer.prepareWriteSequence(null);

        // create new image parameters to set the compression
        // Locale locale = new Locale("en");
        // JPEGImageWriteParam jpegWriteParam = new
        // JPEGImageWriteParam(locale);

        // IIOImage iioImage = new IIOImage(renderedimage, null, iomd);

        IIOImage iioImage = new IIOImage(noAlphaBi, null, iomd);
        writer.write(null, iioImage, writerParam);
        writer.endWriteSequence();
        imageOutStream.flush();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        ImageOutputStream imageToFile = ImageIO.createImageOutputStream(baos);
        writer.setOutput(imageToFile);
        writer.prepareWriteSequence(null);
        writer.write(null, iioImage, writerParam);
        writer.endWriteSequence();
        imageToFile.flush();
        imageToFile.close();
        baos.flush();
        data = baos.toByteArray();
        baos.close();
        writer.dispose();
        imageOutStream.close();
    } catch (IOException e) {
        LOGGER.error("IOException occured", e);
    }
    return data;
}

From source file:org.nekorp.workflow.desktop.servicio.reporte.orden.servicio.OrdenServicioDataFactory.java

private void saveJPG(BufferedImage img, File file) {
    ImageWriter writer = null;/*from  w w w  .jav a 2 s. c o  m*/
    FileImageOutputStream output = null;
    try {
        writer = ImageIO.getImageWritersByFormatName("jpeg").next();
        ImageWriteParam param = writer.getDefaultWriteParam();
        param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        param.setCompressionQuality(1);
        output = new FileImageOutputStream(file);
        writer.setOutput(output);
        IIOImage iioImage = new IIOImage(img, null, null);
        writer.write(null, iioImage, param);
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    } finally {
        try {
            if (writer != null) {
                writer.dispose();
            }
            if (output != null) {
                output.close();
            }
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    }
}

From source file:edu.ku.brc.specify.utilapps.ERDVisualizer.java

public void writeJPEG(File outfile, BufferedImage bufferedImage, float compressionQuality) {
    try {//from w w w  .  j  a va2 s .c om

        long start = System.currentTimeMillis();

        // Find a jpeg writer
        ImageWriter writer = null;
        Iterator<?> iter = ImageIO.getImageWritersByFormatName("jpg");
        if (iter.hasNext()) {
            writer = (ImageWriter) iter.next();
        }

        // Prepare output file
        ImageOutputStream ios = ImageIO.createImageOutputStream(outfile);
        writer.setOutput(ios);

        // Set the compression quality
        ImageWriteParam iwparam = new MyImageWriteParam();
        iwparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        iwparam.setCompressionQuality(compressionQuality);

        // Write the image
        writer.write(null, new IIOImage(bufferedImage, null, null), null);

        // Cleanup
        ios.flush();
        writer.dispose();
        ios.close();

        System.out.println(System.currentTimeMillis() - start);

    } catch (IOException e) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ERDVisualizer.class, e);
        e.printStackTrace();
    }

}

From source file:lucee.runtime.img.Image.java

private void _writeOut(ImageOutputStream ios, String format, float quality, boolean noMeta)
        throws IOException, ExpressionException {
    if (quality < 0 || quality > 1)
        throw new IOException(
                "quality has an invalid value [" + quality + "], value has to be between 0 and 1");
    if (StringUtil.isEmpty(format))
        format = this.format;
    if (StringUtil.isEmpty(format))
        throw new IOException("missing format");

    BufferedImage im = image();// w w  w  .  j av  a  2s  .co  m

    //IIOMetadata meta = noMeta?null:metadata(format);
    IIOMetadata meta = noMeta ? null : getMetaData(null);

    ImageWriter writer = null;
    ImageTypeSpecifier type = ImageTypeSpecifier.createFromRenderedImage(im);
    Iterator<ImageWriter> iter = ImageIO.getImageWriters(type, format);

    if (iter.hasNext()) {
        writer = iter.next();
    }
    if (writer == null)
        throw new IOException("no writer for format [" + format + "] available, available writer formats are ["
                + ListUtil.arrayToList(ImageUtil.getWriterFormatNames(), ",") + "]");

    ImageWriteParam iwp = null;
    if ("jpg".equalsIgnoreCase(format)) {
        ColorModel cm = im.getColorModel();
        if (cm.hasAlpha())
            im = jpgImage(im);
        JPEGImageWriteParam jiwp = new JPEGImageWriteParam(Locale.getDefault());
        jiwp.setOptimizeHuffmanTables(true);
        iwp = jiwp;
    } else
        iwp = writer.getDefaultWriteParam();

    setCompressionModeEL(iwp, ImageWriteParam.MODE_EXPLICIT);
    setCompressionQualityEL(iwp, quality);
    writer.setOutput(ios);
    try {
        writer.write(meta, new IIOImage(im, null, meta), iwp);

    } finally {
        writer.dispose();
        ios.flush();
    }
}

From source file:org.apache.flex.compiler.internal.embedding.transcoders.JPEGTranscoder.java

private byte[] bufferedImageToJPEG(ImageInfo imageInfo, int[] pixels) throws Exception {
    BufferedImage bufferedImage = new BufferedImage(imageInfo.width, imageInfo.height,
            BufferedImage.TYPE_INT_ARGB);
    bufferedImage.setRGB(0, 0, imageInfo.width, imageInfo.height, pixels, 0, imageInfo.width);

    ImageWriter writer = ImageIO.getImageWritersByFormatName("jpeg").next();
    ImageWriteParam writeParam = writer.getDefaultWriteParam();
    ColorModel colorModel = new DirectColorModel(24, 0x00ff0000, 0x0000ff00, 0x000000ff);
    ImageTypeSpecifier imageTypeSpecifier = new ImageTypeSpecifier(colorModel,
            colorModel.createCompatibleSampleModel(1, 1));
    writeParam.setDestinationType(imageTypeSpecifier);
    writeParam.setSourceBands(new int[] { 0, 1, 2 });
    writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);

    float q = 1.0f;
    if (quality != null)
        q = quality.floatValue();/*  www  .j a v  a 2s  . c om*/
    writeParam.setCompressionQuality(q);

    DAByteArrayOutputStream buffer = new DAByteArrayOutputStream();
    writer.setOutput(new MemoryCacheImageOutputStream(buffer));

    IIOImage ioImage = new IIOImage(bufferedImage, null, null);

    writer.write(null, ioImage, writeParam);
    writer.dispose();

    return buffer.getDirectByteArray();
}

From source file:org.bigbluebuttonproject.fileupload.document.impl.FileSystemSlideManager.java

/**
 * This method create thumbImage of the image file given and save it in outFile.
 * Compression quality is also given. thumbBounds is used for calculating the size of the thumb.
 * /*www. ja  v a2 s  .  c  o  m*/
 * @param infile slide image to create thumb
 * @param outfile output thumb file
 * @param compressionQuality the compression quality
 * @param thumbBounds the thumb bounds
 * 
 * @throws IOException Signals that an I/O exception has occurred.
 */
public void resizeImage(File infile, File outfile, float compressionQuality, int thumbBounds)
        throws IOException {
    // Retrieve jpg image to be resized
    Image image = ImageIO.read(infile);

    // get original image size for thumb size calculation
    int imageWidth = image.getWidth(null);
    int imageHeight = image.getHeight(null);

    float thumbRatio = (float) thumbBounds / Math.max(imageWidth, imageHeight);

    int thumbWidth = (int) (imageWidth * thumbRatio);
    int thumbHeight = (int) (imageHeight * thumbRatio);

    // draw original image to thumbnail image object and
    // scale it to the new size on-the-fly
    BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB);
    Graphics2D graphics2D = thumbImage.createGraphics();
    graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);

    // Find a jpeg writer
    ImageWriter writer = null;
    Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpg");
    if (iter.hasNext()) {
        writer = (ImageWriter) iter.next();
    }

    ImageWriteParam iwp = writer.getDefaultWriteParam();
    iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    iwp.setCompressionQuality(compressionQuality);

    // Prepare output file
    ImageOutputStream ios = ImageIO.createImageOutputStream(outfile);
    writer.setOutput(ios);
    // write to the thumb image 
    writer.write(thumbImage);

    // Cleanup
    ios.flush();
    writer.dispose();
    ios.close();
}

From source file:org.codice.alliance.plugin.nitf.NitfPostIngestPlugin.java

private byte[] renderToJpeg2k(final BufferedImage bufferedImage) throws IOException {

    BufferedImage imageToCompress = bufferedImage;

    if (bufferedImage.getColorModel().getNumComponents() == ARGB_COMPONENT_COUNT) {

        imageToCompress = new BufferedImage(bufferedImage.getWidth(), bufferedImage.getHeight(),
                BufferedImage.TYPE_3BYTE_BGR);

        Graphics2D g = imageToCompress.createGraphics();

        g.drawImage(bufferedImage, 0, 0, null);
    }/*from   w  w  w  .  j  a  v a2  s .co m*/

    ByteArrayOutputStream os = new ByteArrayOutputStream();

    J2KImageWriter writer = new J2KImageWriter(new J2KImageWriterSpi());
    J2KImageWriteParam writeParams = (J2KImageWriteParam) writer.getDefaultWriteParam();
    writeParams.setLossless(false);
    writeParams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    writeParams.setCompressionType("JPEG2000");
    writeParams.setCompressionQuality(0.0f);

    ImageOutputStream ios = new MemoryCacheImageOutputStream(os);
    writer.setOutput(ios);
    writer.write(null, new IIOImage(imageToCompress, null, null), writeParams);
    writer.dispose();
    ios.close();

    return os.toByteArray();
}