read Png - Java 2D Graphics

Java examples for 2D Graphics:PNG

Description

read Png

Demo Code


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

import java.io.IOException;
import java.io.InputStream;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;

import javax.imageio.stream.ImageInputStream;

public class Main {
    public static BufferedImage readPng(File f) {
        return readPng(f, false);
    }//w  w  w  .  j a  va2s  .  c o m

    public static BufferedImage readPng(File f, boolean preferBetter) {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(f);
            return readPng(fis, preferBetter);
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (fis != null)
                try {
                    fis.close();
                } catch (Exception e2) {
                }
        }
    }

    public static BufferedImage readPng(InputStream is, boolean preferBetter)
            throws IOException {
        ImageReader ir = getJavaImageReader(preferBetter);
        ImageInputStream iis = ImageIO.createImageInputStream(is);
        ir.setInput(iis);
        return ir.read(0);
    }

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

        for (ImageReader 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);

        return imwriter;
    }
}

Related Tutorials