write Png - Java 2D Graphics

Java examples for 2D Graphics:PNG

Description

write Png

Demo Code


//package com.java2s;
import java.awt.image.BufferedImage;
import java.io.File;

import java.io.FileOutputStream;
import java.io.IOException;

import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.imageio.ImageIO;

import javax.imageio.ImageWriter;

import javax.imageio.stream.ImageOutputStream;

public class Main {
    public static void writePng(File f, BufferedImage bi) {
        writePng(f, bi, false);/*  ww w  . j  av a2 s.  c om*/
    }

    public static void writePng(File f, BufferedImage bi,
            boolean preferBetter) {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(f);
            writePng(fos, bi, preferBetter);
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (fos != null)
                try {
                    fos.close();
                } catch (Exception e2) {
                }
        }

    }

    public static void writePng(OutputStream os, BufferedImage bi,
            boolean preferBetter) throws IOException {
        ImageWriter iw = getJavaImageWriter(preferBetter);
        ImageOutputStream ios = ImageIO.createImageOutputStream(os);
        iw.setOutput(ios);
        iw.write(bi);
        ios.close();
    }

    public static ImageWriter getJavaImageWriter(boolean preferBetter) {
        ImageWriter imwriter = null;
        // com.sun.media.imageioimpl.plugins.png.CLibPNGImageWriter (better)
        // com.sun.imageio.plugins.png.PNGImageWriter
        List<ImageWriter> list = new ArrayList<ImageWriter>();
        for (Iterator<ImageWriter> iter = ImageIO
                .getImageWritersByFormatName("PNG"); iter.hasNext();) {
            list.add(iter.next());
        }

        for (ImageWriter iw : list) {
            String cname = iw.getOriginatingProvider().getPluginClassName();
            if (cname.startsWith("com.sun.media.imageio") && preferBetter) {
                imwriter = iw;
                break;
            }
            if (cname.startsWith("com.sun.imageio.plugins.png.")
                    && !preferBetter) {
                imwriter = iw;
                break;
            }
        }
        if (imwriter == null)
            imwriter = list.get(0); // whatever

        return imwriter;
    }
}

Related Tutorials