save Image File - Java 2D Graphics

Java examples for 2D Graphics:Image File

Description

save Image File

Demo Code


//package com.java2s;

import java.awt.image.BufferedImage;
import java.awt.image.DirectColorModel;
import java.awt.image.WritableRaster;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class Main {
    public static void saveImageFile(String filename, BufferedImage img) {
        File file = new File(filename);
        String suffix = filename.substring(filename.lastIndexOf('.') + 1);

        // png files
        if (suffix.toLowerCase().equals("png")) {
            try {
                ImageIO.write(img, suffix, file);
            } catch (IOException e) {
                e.printStackTrace();// ww w.j  av a  2  s.  c  o  m
            }
        }

        // workaround for jpeg (need to change from ARGB to RGB)
        else if (suffix.toLowerCase().equals("jpg")) {
            WritableRaster raster = img.getRaster();
            WritableRaster newRaster;
            newRaster = raster.createWritableChild(0, 0, img.getWidth(),
                    img.getHeight(), 0, 0, new int[] { 0, 1, 2 });
            DirectColorModel cm = (DirectColorModel) img.getColorModel();
            DirectColorModel newCM = new DirectColorModel(
                    cm.getPixelSize(), cm.getRedMask(), cm.getGreenMask(),
                    cm.getBlueMask());
            BufferedImage rgbBuffer = new BufferedImage(newCM, newRaster,
                    false, null);
            try {
                ImageIO.write(rgbBuffer, suffix, file);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        else { // GIF and BMP are not as popular as PNG/JPG
            System.out.println("Invalid image file type: " + suffix);
        }
    }
}

Related Tutorials