import java.awt.Image;
import java.awt.p_w_picpath.BufferedImage; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Random; import javax.p_w_picpathio.ImageIO; import com.sun.p_w_picpath.codec.jpeg.JPEGCodec; import com.sun.p_w_picpath.codec.jpeg.JPEGEncodeParam; import com.sun.p_w_picpath.codec.jpeg.JPEGImageEncoder; public class testStatic { @SuppressWarnings("restriction") public static String doCompress(String oldFile) throws FileNotFoundException { if (oldFile != null) { Image srcFile=null; String newImage = null; try { File file = new File(oldFile); // 文件不存在 if (!file.exists()) { return null; } /*读取图片信息*/ srcFile = ImageIO.read(file); int new_w = srcFile.getHeight(null); int new_h = srcFile.getHeight(null); int maxWH = 200; if(new_w>maxWH||new_h>maxWH){ if (new_w > new_h) { new_w = maxWH; new_h = maxWH * new_h / new_w; } else { new_w = maxWH * new_w / new_h; new_h = maxWH; } } /* 宽高设定*/ BufferedImage tag = new BufferedImage(new_w, new_h, BufferedImage.TYPE_INT_RGB); tag.getGraphics().drawImage(srcFile, 0, 0, new_w, new_h, null); //随机数 Random rnd = new Random(); int num = rnd.nextInt(89999) + 10000; /*压缩后的文件名 */ String filePrex = oldFile.substring(0, oldFile.lastIndexOf('.')); newImage = filePrex + num + oldFile.substring(filePrex.length()); /*压缩之后临时存放位置*/ FileOutputStream out = new FileOutputStream(newImage); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(tag); //压缩质量 jep.setQuality(1, true); encoder.encode(tag, jep); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ srcFile.flush(); } return newImage; } else { return null; } } //测试 public static void main(String str[]) throws FileNotFoundException { System.out.println(doCompress("D:/aa.jpg")); } }