Example usage for javax.imageio ImageWriter getDefaultWriteParam

List of usage examples for javax.imageio ImageWriter getDefaultWriteParam

Introduction

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

Prototype

public ImageWriteParam getDefaultWriteParam() 

Source Link

Document

Returns a new ImageWriteParam object of the appropriate type for this file format containing default values, that is, those values that would be used if no ImageWriteParam object were specified.

Usage

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  2 s . co 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:com.actelion.research.orbit.imageAnalysis.utils.ImageUtils.java

/**
 * Stores BufferedImage as JPEG2000 encoded file.
 *
 * @param bi/*from   w  w  w  . j av  a 2s. 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.rptools.tokentool.AppActions.java

public static void saveToken(File rptok_file, boolean overwrite) {
    if (rptok_file != null) {
        if (!rptok_file.getName().toUpperCase().endsWith(".RPTOK")) {
            rptok_file = new File(rptok_file.getAbsolutePath() + ".rptok");
        }/*from   w  w  w .  j  ava2  s.c o m*/

        if (rptok_file.exists() && !overwrite) {
            if (!TokenTool.confirm("File exists.  Overwrite?")) {
                return;
            } else {
                rptok_file.delete();
            }
        }

        String tokenName = FilenameUtils.removeExtension(rptok_file.getName());

        try {
            // Write out the token image first or aka POG image.
            File tokenImageFile = File.createTempFile("tokenImage", ".png");

            // PW: This code addes the pHYs chunk to the
            // output png file with X & Y dpi set.
            BufferedImage tokenImg = TokenTool.getFrame().getComposedToken();
            BufferedImage portraitImg = TokenTool.getFrame().getTokenCompositionPanel().getBaseImage();

            ImageWriter writer = getImageWriterBySuffix("png");
            // Created object for outputStream so we can properly close it! No longer locks .png files until app closes!
            ImageOutputStream ios = ImageIO.createImageOutputStream(tokenImageFile);
            writer.setOutput(ios);
            ImageWriteParam param = writer.getDefaultWriteParam();

            PNGMetadata png = new PNGMetadata();
            // 39.375 inches per meter
            // I'm using the image width for the DPI under
            // the assumption that the token fits within
            // one cell.
            int resX = (int) (tokenImg.getWidth() * 39.375f);
            png.pHYs_pixelsPerUnitXAxis = resX;
            png.pHYs_pixelsPerUnitYAxis = resX;
            png.pHYs_unitSpecifier = 1; // Meters - alternative is "unknown"
            png.pHYs_present = true;

            writer.write(null, new IIOImage(tokenImg, null, png), param);
            ios.close();

            // Now write out the Portrait image, here we'll use JPEG to save space
            File portraitImageFile = File.createTempFile("portraitImage", ".jpg");
            writer.reset();
            writer = getImageWriterBySuffix("jpg");
            ios = ImageIO.createImageOutputStream(portraitImageFile);
            writer.setOutput(ios);
            param = writer.getDefaultWriteParam();

            writer.write(null, new IIOImage(portraitImg, null, null), param);
            writer.dispose();
            ios.close();

            // Lets create the token!
            Token _token = new Token();
            Asset tokenImage = null;
            tokenImage = AssetManager.createAsset(tokenImageFile);
            AssetManager.putAsset(tokenImage);
            _token = new Token(tokenName, tokenImage.getId());
            _token.setGMName(tokenName);

            // Jamz: Below calls not needed, creates extra entries in XML preventing token image from changing inside MapTool
            //_token.setImageAsset(tokenImage.getName());
            //_token.setImageAsset(tokenImage.getName(), tokenImage.getId());

            // set the image shape
            Image image = ImageIO.read(tokenImageFile);
            _token.setShape(TokenUtil.guessTokenType(image));

            // set the height/width, fixes dragging to stamp layer issue
            _token.setHeight(tokenImg.getHeight());
            _token.setWidth(tokenImg.getWidth());

            // set the portrait image asset
            Asset portrait = AssetManager.createAsset(portraitImageFile); // Change for portrait
            AssetManager.putAsset(portrait);
            _token.setPortraitImage(portrait.getId());

            // Time to write out the .rptok token file...
            PackedFile pakFile = null;
            try {
                pakFile = new PackedFile(rptok_file);
                saveAssets(_token.getAllImageAssets(), pakFile);
                pakFile.setContent(_token);
                BufferedImage thumb = ImageUtil.createCompatibleImage(image, THUMB_SIZE, THUMB_SIZE, null);
                pakFile.putFile(FILE_THUMBNAIL, ImageUtil.imageToBytes(thumb, "png"));
                pakFile.setProperty(PROP_VERSION, TokenToolFrame.VERSION);
                pakFile.save();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (pakFile != null)
                    pakFile.close();
                tokenImageFile.delete();
                portraitImageFile.delete();
            }

        } catch (IOException ioe) {
            ioe.printStackTrace();
            TokenTool.showError("Unable to write image: " + ioe);
        }
    }
}

From source file:com.sketchy.utils.image.SketchyImage.java

public static void save(SketchyImage sketchyImage, File file) throws Exception {
    if (!file.getParentFile().canWrite()) {
        throw new Exception("Can not write to File: " + file.getPath() + "!");
    }//from  w ww  .j a  va2 s . com

    if (!StringUtils.endsWithIgnoreCase(file.getName(), ".png")) {
        throw new Exception("Can not save SketchyImage! Must be a .png file!");
    }

    Iterator<ImageWriter> imageWriters = ImageIO.getImageWritersByFormatName("png");
    ImageWriter imageWriter = null;
    if (imageWriters.hasNext()) { // Just get first one
        imageWriter = imageWriters.next();
    }
    if (imageWriter == null) {
        // this should never happen!! if so.. we got problems
        throw new Exception("Can not find ImageReader for .png Files!");
    }

    ImageOutputStream os = null;
    try {
        os = ImageIO.createImageOutputStream(file);
        imageWriter.setOutput(os);

        ImageWriteParam imageWriterParam = imageWriter.getDefaultWriteParam();
        IIOMetadata metadata = imageWriter.getDefaultImageMetadata(
                ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_BYTE_BINARY),
                imageWriterParam);

        String metaDataFormatName = metadata.getNativeMetadataFormatName();
        IIOMetadataNode metaDataNode = (IIOMetadataNode) metadata.getAsTree(metaDataFormatName);

        NodeList childNodes = metaDataNode.getElementsByTagName("pHYs");
        IIOMetadataNode physNode = null;
        if (childNodes.getLength() == 0) {
            physNode = new IIOMetadataNode("pHYs");
            physNode.setAttribute("pixelsPerUnitXAxis",
                    Integer.toString((int) Math.ceil(sketchyImage.dotsPerMillimeterWidth * 1000)));
            physNode.setAttribute("pixelsPerUnitYAxis",
                    Integer.toString((int) Math.ceil(sketchyImage.dotsPerMillimeterHeight * 1000)));
            physNode.setAttribute("unitSpecifier", "meter"); // always meter
            metaDataNode.appendChild(physNode);
        } else {
            for (int nodeIdx = 0; nodeIdx < childNodes.getLength(); nodeIdx++) {
                physNode = (IIOMetadataNode) childNodes.item(nodeIdx);
                physNode.setAttribute("pixelsPerUnitXAxis",
                        Integer.toString((int) Math.ceil(sketchyImage.dotsPerMillimeterWidth * 1000)));
                physNode.setAttribute("pixelsPerUnitYAxis",
                        Integer.toString((int) Math.ceil(sketchyImage.dotsPerMillimeterHeight * 1000)));
                physNode.setAttribute("unitSpecifier", "meter"); // always meter
                metaDataNode.appendChild(physNode);
            }
        }
        metadata.setFromTree(metaDataFormatName, metaDataNode);
        imageWriter.write(new IIOImage(sketchyImage.image, null, metadata));
        os.flush();
    } catch (Exception e) {
        throw new Exception("Error Saving SketchyImage File: " + file.getPath() + "!  " + e.getMessage());
    } finally {
        IOUtils.closeQuietly(os);
    }
}

From source file:com.ackpdfbox.app.imageio.ImageIOUtil.java

/**
 * Writes a buffered image to a file using the given image format.
 * Compression is fixed for PNG, GIF, BMP and WBMP, dependent of the quality
 * parameter for JPG, and dependent of bit count for TIFF (a bitonal image
 * will be compressed with CCITT G4, a color image with LZW). Creating a
 * TIFF image is only supported if the jai_imageio library is in the class
 * path./*w  w  w. j a v  a  2  s. com*/
 *
 * @param image the image to be written
 * @param formatName the target format (ex. "png")
 * @param output the output stream to be used for writing
 * @param dpi the resolution in dpi (dots per inch) to be used in metadata
 * @param quality quality to be used when compressing the image (0 &lt;
 * quality &lt; 1.0f)
 * @return true if the image file was produced, false if there was an error.
 * @throws IOException if an I/O error occurs
 */
public static boolean writeImage(BufferedImage image, String formatName, OutputStream output, int dpi,
        float quality) throws IOException {
    ImageOutputStream imageOutput = null;
    ImageWriter writer = null;
    try {
        // find suitable image writer
        Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(formatName);
        ImageWriteParam param = null;
        IIOMetadata metadata = null;
        // Loop until we get the best driver, i.e. one that supports
        // setting dpi in the standard metadata format; however we'd also 
        // accept a driver that can't, if a better one can't be found
        while (writers.hasNext()) {
            if (writer != null) {
                writer.dispose();
            }
            writer = writers.next();
            param = writer.getDefaultWriteParam();
            metadata = writer.getDefaultImageMetadata(new ImageTypeSpecifier(image), param);
            if (metadata != null && !metadata.isReadOnly() && metadata.isStandardMetadataFormatSupported()) {
                break;
            }
        }
        if (writer == null) {
            LOG.error("No ImageWriter found for '" + formatName + "' format");
            StringBuilder sb = new StringBuilder();
            String[] writerFormatNames = ImageIO.getWriterFormatNames();
            for (String fmt : writerFormatNames) {
                sb.append(fmt);
                sb.append(' ');
            }
            LOG.error("Supported formats: " + sb);
            return false;
        }

        // compression
        if (param != null && param.canWriteCompressed()) {
            param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            if (formatName.toLowerCase().startsWith("tif")) {
                // TIFF compression
                TIFFUtil.setCompressionType(param, image);
            } else {
                param.setCompressionType(param.getCompressionTypes()[0]);
                param.setCompressionQuality(quality);
            }
        }

        if (formatName.toLowerCase().startsWith("tif")) {
            // TIFF metadata
            TIFFUtil.updateMetadata(metadata, image, dpi);
        } else if ("jpeg".equals(formatName.toLowerCase()) || "jpg".equals(formatName.toLowerCase())) {
            // This segment must be run before other meta operations,
            // or else "IIOInvalidTreeException: Invalid node: app0JFIF"
            // The other (general) "meta" methods may not be used, because
            // this will break the reading of the meta data in tests
            JPEGUtil.updateMetadata(metadata, dpi);
        } else {
            // write metadata is possible
            if (metadata != null && !metadata.isReadOnly() && metadata.isStandardMetadataFormatSupported()) {
                setDPI(metadata, dpi, formatName);
            }
        }

        // write
        imageOutput = ImageIO.createImageOutputStream(output);
        writer.setOutput(imageOutput);
        writer.write(null, new IIOImage(image, null, metadata), param);
    } finally {
        if (writer != null) {
            writer.dispose();
        }
        if (imageOutput != null) {
            imageOutput.close();
        }
    }
    return true;
}

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 {// w  w  w  .j ava 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:org.shredzone.cilla.service.resource.ImageProcessorImpl.java

/**
 * Writes a JPEG file with adjustable compression quality.
 *
 * @param image//w w  w.  j av a 2  s  .  c o  m
 *            {@link BufferedImage} to write
 * @param out
 *            {@link ImageOutputStream} to write to
 * @param quality
 *            Compression quality between 0.0f (worst) and 1.0f (best)
 */
private void jpegQualityWriter(BufferedImage image, ImageOutputStream out, float quality) throws IOException {
    ImageWriter writer = ImageIO.getImageWritersByFormatName("jpeg").next();

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

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

    writer.setOutput(out);
    writer.write(null, ioImage, iwp);
    writer.dispose();
}

From source file:de.jwic.ecolib.controls.chart.ChartControl.java

public void renderImage() throws IOException {
    // create image to draw into
    BufferedImage bi = new BufferedImage(width < 10 ? 10 : width, height < 10 ? 10 : height,
            BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = bi.createGraphics();

    if (chart != null) {
        chart.setBackgroundPaint(Color.WHITE);
        chart.draw(g2d, new Rectangle2D.Double(0, 0, width < 10 ? 10 : width, height < 10 ? 10 : height));
    } else {/*  w  ww.ja va2 s .c o  m*/
        g2d.setColor(Color.BLACK);
        g2d.drawString("No chart has been assigned.", 1, 20);
    }
    // finish drawing
    g2d.dispose();

    // write image data into output stream
    ByteArrayOutputStream out = getImageOutputStream();
    out.reset();
    // create a PNG image
    ImageWriter imageWriter = new PNGImageWriter(null);
    ImageWriteParam param = imageWriter.getDefaultWriteParam();
    imageWriter.setOutput(new MemoryCacheImageOutputStream(out));
    imageWriter.write(null, new IIOImage(bi, null, null), param);
    imageWriter.dispose();

    setMimeType(MIME_TYPE_PNG);
}

From source file:io.warp10.script.processing.Pencode.java

@Override
public Object apply(WarpScriptStack stack) throws WarpScriptException {
    Object top = stack.pop();/* ww w. j ava2 s. c  o 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 = () -> {//from ww  w.jav a2 s . 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;
}