工具类四:ImageUtil

工具类4:ImageUtil
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.UUID;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper;
import org.codehaus.xfire.client.Client;
import com.mortennobel.imagescaling.ResampleOp;
/**
* 图片处理工具
* @author ziyuzhang
*
*/
public class ImageUtil {

private static final int BUFFER_SIZE = 16 * 1024;



    /**
     * 处理图片并保存  一张原图和一张缩小后的图片  小图可用于手机端
     * @param upload             大图对象
     * @param uploadFileName     图片原名
     * @param webPath            工程部署的绝对地址
     * @param filePath           图片目录
     * @return   为一字符数字,0位置 为原图片位置,1位置为压缩后图片位置,2位置为压缩后图片高度,3位置为压缩后图片宽度,4位置为压缩后图片大小
     */
public static String[] uploadImages(File upload, String uploadFileName,String webPath,String filePath) {

StringTokenizer tokenizer = new StringTokenizer(uploadFileName, ".");
String ext="";
while(tokenizer.hasMoreTokens()){
ext = tokenizer.nextToken();
}

//大图的名字
String filename = ImageUtil.getUUID()+"."+ext;
//保存大图
if(!ImageUtil.saveFile(upload,webPath,filePath,filename)){
         return null;
}

String afterFileName = ImageUtil.getUUID();
//小图的名字
String smallname =   afterFileName + "." + ext;
String smallPath = webPath + filePath + smallname;
     // 产生一张新的截图
String[] fileinfo =  ImageUtil.resizeImage(upload, smallPath,ConfigUtil.getIntValue("image.width"),
ConfigUtil.getIntValue("image.height"),ext);
if(null == fileinfo){
    return new String[]{"/" + filePath + filename,"/" + filePath + filename,
             null,null,null};
}else{
    return new String[]{"/" + filePath + filename,"/" + filePath + smallname,
                 fileinfo[0],fileinfo[1],fileinfo[2]};
}

}

/**
* 对应图片key为 upload
* 保存附件 限制大小100M
* @param response
* @param request
* @return
*/
   public static String getfile(HttpServletResponse  response,HttpServletRequest  request) {


SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
         // 根据服务器的文件保存地址找到项目部署的绝对地址
         String webPath = ServletActionContext.getServletContext().getRealPath("/")  ;
         String filePath ="upload/"+sdf.format(new Date())+"/";
//文件保存目录路径
String savePath = webPath+ "upload/";
//最大文件大小
long maxSize = 1024*1024*100;
response.setContentType("text/html; charset=UTF-8");
if (!ServletFileUpload.isMultipartContent(request)) {
return "erro";
}
//如果目录不存在则创建
if (!(new File(savePath).exists())) {
if (!(new File(savePath).mkdirs())) {
return "erro";
}
}

//检查目录写权限
if (!(new File(savePath)).canWrite()) {
return "erro";
}
MultiPartRequestWrapper   mul = (MultiPartRequestWrapper)request;
File[] imageFiles = mul.getFiles("upload");
String[] filesss = mul.getFileNames("upload");
if (imageFiles != null && imageFiles.length >0) {

String fileName = filesss[0];
long fileSize = imageFiles[0].length();
//检查文件大小
if (fileSize > maxSize) {
return "erro";
}
//检查扩展名
String fileExt = fileName.substring(
fileName.lastIndexOf(".") + 1).toLowerCase();

SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
//保存图片到硬盘
ImageUtil.saveFile(imageFiles[0], webPath, filePath, newFileName);

filePath = webPath + filePath+newFileName ;
}   

    return filePath;
    }



/**
* 将文件保存到制定位置,路径不存在自动创建
*
* @param file
*            要保存的文件
* @param webPath
*            工程部署的绝对路径
* @param filePath
*            文件夹的相对路径
* @param filename
*            文件名
* @return
*/
public static boolean saveFile(File file, String webPath, String filePath,
String filename) {

if (new File(webPath + filePath).exists()) {
webPath = webPath + filePath + "/" + filename;
File dstFile = new File(webPath);
if (copy(file, dstFile)) {
return true;
}

} else {
if (new File(webPath + filePath).mkdirs()) {
webPath = webPath + filePath + "/" + filename;
File dstFile = new File(webPath);
if (copy(file, dstFile)) {
return true;
}

}

}
return false;

}

/**
* 把源文件对象复制成目标文件对象
*
* @param src
*            源文件
* @param dst
*            目标文件
* @return
*/
public static boolean copy(File src, File dst) {
boolean result = false;
InputStream in = null;
OutputStream out = null;
try {
in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE);
out = new BufferedOutputStream(new FileOutputStream(dst),
BUFFER_SIZE);
byte[] buffer = new byte[BUFFER_SIZE];
int len = 0;
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
result = true;
} catch (Exception e) {
e.printStackTrace();
result = false;
} finally {
if (null != in) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != out) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}

/**
* 接收File输出图片
* 以图片高为标准 按比例缩减图片
* @param file
*            原图片对象
* @param writePath
*            小图片存放的路径
* @param width
*            宽
* @param height
*            高
* @param format
*            图片格式
* @return
*/
public static String[]  resizeImage(File file, String writePath,
Integer width, Integer height, String format) {

try {
BufferedImage inputBufImage = ImageIO.read(file);
inputBufImage.getType();

System.out.println("转前图片高度和宽度:" + inputBufImage.getHeight() + ":"
+ inputBufImage.getWidth());
if(height >=inputBufImage.getHeight() || width >= inputBufImage.getWidth()){

return null;
}else{
//double dd = inputBufImage.getHeight() / height;
//width = (int) (inputBufImage.getWidth() / dd);
//height = (int) (inputBufImage.getHeight() / dd);
// 转换
ResampleOp resampleOp = new ResampleOp(width, height);
BufferedImage rescaledTomato = resampleOp.filter(inputBufImage,null);
File fil = new File(writePath);
ImageIO.write(rescaledTomato, format,fil);
System.out.println("转后图片高度和宽度:" + rescaledTomato.getHeight() + ":"
+ rescaledTomato.getWidth());
return new String[]{rescaledTomato.getHeight()+"",rescaledTomato.getWidth()+"",fil.length()+""};
}
} catch (IOException e) {
e.printStackTrace();
return null;
}

}

public static String lastname(String name) {
String[] ls = name.split("\\.");

return ls[ls.length - 1];
}

public static String getUUID() {

return UUID.randomUUID().toString().replaceAll("-", "");
}
}
转自:http://lucien-zzy.iteye.com/blog/2009507