compress Image - Java 2D Graphics

Java examples for 2D Graphics:Image Compress

Description

compress Image

Demo Code


//package com.java2s;
import javax.imageio.ImageIO;

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Main {


    public static File compressImg(File oldfile, int size, File newfile) {
        if (!newfile.exists())
            try {
                newfile.createNewFile();
            } catch (IOException e1) {
                return null;
            }/*from w ww .java2s  .  c  om*/
        BufferedImage bi;
        try {
            bi = ImageIO.read(new FileInputStream(oldfile));
            int width = bi.getWidth();
            int height = bi.getHeight();
            if (width > size || height > size) {
                Image image;
                if (width > height) {
                    height = (int) (bi.getHeight() / (bi.getWidth() * 1d) * size);
                    image = bi.getScaledInstance(size, height,
                            Image.SCALE_DEFAULT);
                } else {
                    width = (int) (bi.getWidth() / (bi.getHeight() * 1d) * size);
                    image = bi.getScaledInstance(width, size,
                            Image.SCALE_DEFAULT);
                }
                ImageIO.write(toBufferedImage(image), "png",
                        new FileOutputStream(newfile));
                return newfile;
            } else {
                return oldfile;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static BufferedImage toBufferedImage(Image image) {
        if (image instanceof BufferedImage) {
            return (BufferedImage) image;
        }
        image = new ImageIcon(image).getImage();
        BufferedImage bimage = null;
        GraphicsEnvironment ge = GraphicsEnvironment
                .getLocalGraphicsEnvironment();
        try {
            int transparency = Transparency.TRANSLUCENT;
            GraphicsDevice gs = ge.getDefaultScreenDevice();
            GraphicsConfiguration gc = gs.getDefaultConfiguration();
            bimage = gc.createCompatibleImage(image.getWidth(null),
                    image.getHeight(null), transparency);
        } catch (HeadlessException e) {
        }
        if (bimage == null) {
            int type = BufferedImage.TYPE_INT_RGB;
            bimage = new BufferedImage(image.getWidth(null),
                    image.getHeight(null), type);
        }
        Graphics g = bimage.createGraphics();
        g.drawImage(image, 0, 0, null);
        g.dispose();
        return bimage;
    }
}

Related Tutorials