Java examples for 2D Graphics:Image Compress
compress Picture
//package com.java2s; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; public class Main { public static boolean compressPic(String inputFile, String outFile, int width, int height, boolean proportion) { try {//from w w w.j av a2 s.co m // File file = new File(inputFile); if (!file.exists()) { return false; } Image img = ImageIO.read(file); // ? if (img.getWidth(null) == -1) { return false; } else { int newWidth; int newHeight; // ? if (proportion == true) { // ? double rate1 = ((double) img.getWidth(null)) / (double) width + 0.1; double rate2 = ((double) img.getHeight(null)) / (double) height + 0.1; // double rate = rate1 > rate2 ? rate1 : rate2; newWidth = (int) ((img.getWidth(null)) / rate); newHeight = (int) ((img.getHeight(null)) / rate); } else { newWidth = width; // ? newHeight = height; // ? } // /* * if (img.getWidth(null) < width && img.getHeight(null) < * height) { newWidth = img.getWidth(null); newHeight = * img.getHeight(null); } */ BufferedImage tag = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB); // Image.SCALE_SMOOTH ? ,? tag.getGraphics().drawImage( img.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH), 0, 0, null); FileOutputStream out = new FileOutputStream(outFile); // JPEGImageEncoder? //JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); -yrh comment //encoder.encode(tag); -yrh comment out.close(); } } catch (IOException ex) { ex.printStackTrace(); } return true; } }