package com.shengling.discount.util;
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
public class ImageCutUtils {
/**
* 缩放图片大小
* @param inputFile
*
源图片
* @param outFile
*
绽放后图片
* @param width
*
宽度
* @param height
*
高度
* @param proportion
*
是否等比缩放
* @return
* author : linfanhe 2012-4-26
*/
public static boolean s_pic(String inputFile , String outFile ,int width , int height, boolean proportion) {
// BufferedImage image;
// String NewFileName;
//
建立输出文件对象
File file = new File(outFile);
FileOutputStream tempout = null;
try {
tempout = new FileOutputStream(file);
} catch (Exception ex) {
System.out.println(ex.toString());
}
Image img = null;
Toolkit tk = Toolkit.getDefaultToolkit();
Applet app = new Applet();
MediaTracker mt = new MediaTracker(app);
try {
img = tk.getImage(inputFile);
mt.addImage(img, 0);
mt.waitForID(0);
} catch (Exception e) {
e.printStackTrace();
}
if(img == null){
return false;
}
if (img.getWidth(null) == -1) {
return false;
} else {
int new_w;
int new_h;
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;
new_w = (int) ((img.getWidth(null)) / rate);
new_h = (int) ((img.getHeight(null)) / rate);
} else {
new_w = width;
//输出的图片宽度
new_h = height;
//输出的图片高度
}
// 如果图片小于目标图片则不进行转换
if(img.getWidth(null) < width && img.getHeight(null) < height){
new_w = img.getWidth(null);
new_h = img.getHeight(null);
}
BufferedImage buffImg = new BufferedImage(new_w, new_h,
BufferedImage.TYPE_INT_RGB);
Graphics g = buffImg.createGraphics();
g.setColor(Color.white);
g.fillRect(0, 0, new_w, new_h);
g.drawImage(img, 0, 0, new_w, new_h, null);
g.dispose();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(tempout);
try {
encoder.encode(buffImg);
tempout.close();
} catch (IOException ex) {
System.out.println(ex.toString());
}
}
return true;
}
public static void main(String[] args) {
boolean flag=ImageCutUtils.s_pic("d:/1.gif", "d:/13.jpg",1024,768,true);
if(flag){
System.out.println("裁剪正确");
}
/*
boolean b=new File("d:/google.sql").delete();
if(b){
System.out.println("删除");
}
System.out.println("未删除");
*/
}
}