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:nl.softwaredesign.exporter.ODTExportFormat.java

/**
 * TODO Move to utility class?//from   ww w  .  j  av a 2  s .c  o  m
 * Extract the content data (bytes) from the given image.
 * @param icon image to get bytes for
 * @param format desired format for image
 * @param background Color to use as background if transparency in image
 * @param width Desired width of the image in the byte array
 * @param height Desired width of the image in the byte array
 * @return the bytes of the image
 * @throws IOException
 */
private byte[] imageToBytes(ImageIcon icon, String format, Color background, int width, int height)
        throws IOException {
    Iterator writers = ImageIO.getImageWritersByFormatName(format);
    ImageWriter writer = (ImageWriter) writers.next();
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    ImageOutputStream ios = ImageIO.createImageOutputStream(output);
    writer.setOutput(ios);
    BufferedImage img;
    if ("png".equalsIgnoreCase(format) || "gif".equalsIgnoreCase(format)) {
        img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    } else {
        img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    }
    WaitingObserver observer = new WaitingObserver();
    if (!img.getGraphics().drawImage(icon.getImage(), 0, 0, width, height, background, observer)) {
        try {
            observer.waitForDone();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return new byte[0];
        }
    }
    IIOMetadata metadata = writer.getDefaultImageMetadata(new ImageTypeSpecifier(img),
            writer.getDefaultWriteParam());
    if (format.equalsIgnoreCase("jpg")) {
        Element tree = (Element) metadata.getAsTree("javax_imageio_jpeg_image_1.0");
        Element jfif = (Element) tree.getElementsByTagName("app0JFIF").item(0);
        jfif.setAttribute("Xdensity", Integer.toString(72));
        jfif.setAttribute("Ydensity", Integer.toString(72));
        jfif.setAttribute("resUnits", "1");
        metadata.setFromTree("javax_imageio_jpeg_image_1.0", tree);
    } else {
        double dotsPerMilli = 7.2 / 2.54;
        IIOMetadataNode horiz = new IIOMetadataNode("HorizontalPixelSize");
        horiz.setAttribute("value", Double.toString(dotsPerMilli));
        IIOMetadataNode vert = new IIOMetadataNode("VerticalPixelSize");
        vert.setAttribute("value", Double.toString(dotsPerMilli));
        IIOMetadataNode dim = new IIOMetadataNode("Dimension");
        dim.appendChild(horiz);
        dim.appendChild(vert);
        IIOMetadataNode root = new IIOMetadataNode("javax_imageio_1.0");
        root.appendChild(dim);
        metadata.mergeTree("javax_imageio_1.0", root);
    }

    writer.write(null, new IIOImage(img, null, metadata), null);
    return output.toByteArray();
}

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();// ww  w. j  a v  a2 s  .c  o m
    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.
 * /*w  w  w  .j a v  a 2  s  .co 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.dcm4che.tool.dcm2jpg.Dcm2Jpg.java

public static void listSupportedImageWriters(String format) {
    System.out.println(MessageFormat.format(rb.getString("writers"), format));
    Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName(format);
    while (it.hasNext()) {
        ImageWriter writer = it.next();
        ImageWriteParam param = writer.getDefaultWriteParam();
        System.out.println(MessageFormat.format(rb.getString("writer"), writer.getClass().getName(),
                param.canWriteCompressed(), param.canWriteProgressive(), param.canWriteTiles(),
                param.canOffsetTiles(),//from   www .j a  va  2  s  .  c o  m
                param.canWriteCompressed() ? Arrays.toString(param.getCompressionTypes()) : null));
    }
}

From source file:org.dcm4che2.tool.dcm2jpg.Dcm2Jpg.java

private void encodeByImageIO(BufferedImage bi, File dest) throws IOException {
    ImageWriter writer = getImageWriter(imageWriterClassname);
    ImageOutputStream out = null;
    try {//from w  w w. ja  va 2  s.co m
        out = ImageIO.createImageOutputStream(dest);
        writer.setOutput(out);
        ImageWriteParam iwparam = writer.getDefaultWriteParam();
        if (iwparam.canWriteCompressed()) {
            iwparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            String[] compressionTypes = iwparam.getCompressionTypes();
            if (compressionTypes != null && compressionTypes.length > 0) {
                if (compressionType != null || iwparam.getCompressionType() == null) {
                    for (int i = 0; i < compressionTypes.length; i++) {
                        if (compressionType == null
                                || compressionTypes[i].compareToIgnoreCase(compressionType) == 0) {
                            iwparam.setCompressionType(compressionTypes[i]);
                            break;
                        }
                    }
                }
            }
            if (imageQuality != null)
                iwparam.setCompressionQuality(imageQuality);
        } else if (imageQuality != null) {
            System.out.println("Selected Image Writer can not compress! imageQuality is ignored!");
        }
        writer.write(null, new IIOImage(bi, null, null), iwparam);
    } finally {
        CloseUtils.safeClose(out);
        writer.dispose();
    }
}

From source file:org.dcm4che2.tool.dcm2jpg.Dcm2Jpg.java

private void showImageWriters() {
    ImageWriter writer;
    System.out.println("ImageWriters for format name:" + formatName);
    int i = 0;/*from  www . jav  a 2 s .c  o m*/
    for (Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName(formatName); it.hasNext();) {
        writer = it.next();
        System.out.println("Writer[" + (i++) + "]: " + writer.getClass().getName() + ":");
        System.out.println("   Write Param:");
        ImageWriteParam param = writer.getDefaultWriteParam();
        System.out.println("       canWriteCompressed:" + param.canWriteCompressed());
        System.out.println("      canWriteProgressive:" + param.canWriteProgressive());
        System.out.println("            canWriteTiles:" + param.canWriteTiles());
        System.out.println("           canOffsetTiles:" + param.canOffsetTiles());
        if (param.canWriteCompressed()) {
            String[] types = param.getCompressionTypes();
            System.out.println("   Compression Types:");
            if (types != null && types.length > 0) {
                for (int j = 0; j < types.length; j++) {
                    System.out.println("           Type[" + j + "]:" + types[j]);
                }
            }
        }
        System.out.println("-----------------------------");
    }
}

From source file:org.deegree.securityproxy.wms.responsefilter.clipping.SimpleRasterClipper.java

private ImageWriteParam configureWriterParameters(String format, ImageWriter imageWriter) {
    ImageWriteParam writerParam = imageWriter.getDefaultWriteParam();
    if (JPG_FORMAT.equals(format)) {
        writerParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        writerParam.setCompressionQuality(1f);
    }//from   w w  w .ja v a2  s .c o  m
    return writerParam;
}

From source file:org.eclipse.birt.chart.device.svg.SVGGraphics2D.java

private Element createEmbeddeImage(BufferedImage img) {
    if (img == null) {
        return null;
    }//from w ww .j av a  2  s  .c  o  m

    int width = img.getWidth();
    int height = img.getHeight();
    ImageWriter iw = ImageWriterFactory.instance().createByFormatName("png"); //$NON-NLS-1$
    ByteArrayOutputStream baos = new ByteArrayOutputStream(8192 * 2);
    String sUrl = null;
    try {
        final ImageOutputStream ios = SecurityUtil.newImageOutputStream(baos);
        ImageWriteParam iwp = iw.getDefaultWriteParam();
        iw.setOutput(ios);
        iw.write((IIOMetadata) null, new IIOImage(img, null, null), iwp);
        img.flush();
        ios.close();
        sUrl = SVGImage.BASE64 + new String(Base64.encodeBase64(baos.toByteArray()));
    } catch (Exception ex) {
        logger.log(ex);
    } finally {
        iw.dispose();
    }

    Element elemG = dom.createElement("g"); //$NON-NLS-1$
    elemG.setAttribute("id", "img_" + img.hashCode()); //$NON-NLS-1$//$NON-NLS-2$
    Element elem = dom.createElement("image"); //$NON-NLS-1$
    elem.setAttribute("x", "0"); //$NON-NLS-1$//$NON-NLS-2$
    elem.setAttribute("y", "0"); //$NON-NLS-1$ //$NON-NLS-2$
    elem.setAttribute("width", Integer.toString(width)); //$NON-NLS-1$
    elem.setAttribute("height", Integer.toString(height)); //$NON-NLS-1$
    elem.setAttribute("xlink:href", sUrl); //$NON-NLS-1$
    elemG.appendChild(elem);

    return elemG;
}

From source file:org.eclipse.birt.chart.device.svg.SVGImage.java

public SVGImage(Image image, URL url, byte[] data) {
    super();/*from  www.  j  av  a 2  s .c  o m*/
    this.image = image;
    this.url = url;
    this.data = data;
    if (url == null && data == null && image instanceof BufferedImage) {
        ImageWriter iw = ImageWriterFactory.instance().createImageWriter("png", "html"); //$NON-NLS-1$ //$NON-NLS-2$

        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream(2048);
            ImageOutputStream ios = SecurityUtil.newImageOutputStream(baos);
            ImageWriteParam iwp = iw.getDefaultWriteParam();
            iw.setOutput(ios);
            iw.write((IIOMetadata) null, new IIOImage((BufferedImage) image, null, null), iwp);
            ios.close();
            this.data = baos.toByteArray();
            baos.close();
        } catch (IOException e) {
            // do nothing
        } finally {
            iw.dispose();
        }

    }
}