图片批量上传(含压缩图片分辨率)

<div id="FileList">
	<input type=file name="uploadFile[0].file" onkeydown="return false" id="file"/>&nbsp;
	<input type="button"  value=" 添加 " onclick="Addfile_()" />
</div>

//添加上传照片的浏览框
var count = 0;   
function Addfile_(){ 
	if(count > 3) 
	{
		alert("一次最多上传5个照片!");
		return;
	}
   count += 1;   
   var FileList = document.getElementById("FileList");   
   var div = document.createElement("div");   
   var inputTxt = document.createElement("input");   //上传照片浏览框
   inputTxt.type = "file";   
   inputTxt.name = "uploadFile["+count+"].file";   
   inputTxt.onkeydown="return false";
   inputTxt.id="file";
   var space = document.createTextNode(" ");//创建一空格
   var btn = document.createElement("input");   //删除照片按钮
   btn.type = "button";   
   btn.value = " 删除 ";   
   btn.className = "form_1" ;
   btn.onclick = function(){   
         this.parentNode.parentNode.removeChild(this.parentNode);   
         count -= 1;   
   	}   
	 var brEle = document.createElement("br"); 
   div.appendChild(inputTxt); 
   div.appendChild(space); 
   div.appendChild(btn);   
   div.appendChild(brEle); 
   FileList.appendChild(div);   
} 
//验证
function isSameName(pixname)
{
	var s=0;
	var filename = new Array();
	var frm = document.getElementsByTagName('input');  
  for(var i=0;i<frm.length;i++){
     if(frm[i].type  ==  'file' && frm[i].name.indexOf(pixname)!=-1)
    	{          	 
				var iname = frm[i].value; 
				var string_arr = iname.split("\\");       		 
				filename[s] = string_arr[string_arr.length-1];			  
				s++;
				if(iname==''){   
				 alert("照片不能为空!");	
				 return false;	
				}  		
			}		    
  }
  for(var j=0;j<filename.length;j++)
  {
  		var re=/(.*)\.(jpg|bmp|gif)$/;
  		if(!re.exec(filename[j]))
  		{
  			alert("照片"+(j+1)+"格式不正确!");
				return false;	
  		}
  }	    
  for(var j=0;j<filename.length-1;j++){	
 		var uname = filename[j];   
 		for(var k=j+1;k<filename.length;k++)
 		{
 			var sname = filename[k];
 			if (uname == sname)
 			{     
  			alert("照片"+(j+1)+"与"+"照片"+(k+1)+"重名!");
  			return false;			
 			}
 		}
  }
  return true;
}

public String optUploadFile(ActionForm Form);		
	List<FormFile> fileList = new ArrayList<FormFile>();
	if (form.getMultipartRequestHandler() != null)
	{
		/**
		 * 这里使用的是struts的 MultipartRequestHandler 得到页面传过来的所有file类型的表单元素
		 */
		Hashtable fileht = form.getMultipartRequestHandler().getFileElements();
		for (Enumeration e = fileht.keys(); e.hasMoreElements();)
		{
			String key = (String) e.nextElement();
			FormFile file = (FormFile) fileht.get(key);
			fileList.add(file);
		}
		for (FormFile file : fileList)
		{
			Date time = new Date();    
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-ddHHmmssMM");
			String date = formatter.format(time).replace("", "");
			if (file == null){
				continue;
			}
			//得到上传文件的后缀名
			String type=file.getFileName().substring(file.getFileName().lastIndexOf("."), file.getFileName().length());
			try
			{				
					File ff = new File("/路径");
					if(!ff.exists()){
						ff.mkdirs();
					}
					writeFile("/路径/文件名", file.getInputStream());
					//将照片按尺寸缩放*/
					ImageDealWith.imageToDeal("/路径/"+"文件名");
					Thread.sleep(1000);
					message="success";
			} catch (Exception e)
			{
				e.printStackTrace();
			}	
	}
}

public static File writeFile(String path, InputStream is)
{
	File f = createFileIfNotExist(path);
	byte[] buffer = new byte[8192];
	OutputStream fos = null;
	int readByte = 0;
	try
	{
		fos = new FileOutputStream(f);
		while ((readByte = is.read(buffer, 0, 8192)) != -1)
		{
			fos.write(buffer, 0, readByte);
		}
		fos.flush();
	} catch (FileNotFoundException e)
	{
		e.printStackTrace();
	} catch (IOException e)
	{
		e.printStackTrace();
	} finally
	{
		try
		{
			if (is != null)
			{
				is.close();
				is = null;
			}

			if (fos != null)
			{
				fos.close();
				fos = null;
			}

			
		} catch (IOException e)
		{
			e.printStackTrace();
		}
	}
	return f;
}
		
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.awt.image.ColorConvertOp;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.io.*;
import javax.imageio.ImageIO;

import org.apache.commons.validator.GenericValidator;

public class ImageDealWith
{

	private static String	types	= "jpg|gif|jpeg|png|bmp";

	/** */
	/**
	 * 图像切割
	 * 
	 * @param srcImageFile 源图像地址
	 * @param descDir 切片目标文件夹
	 * @param destWidth 目标切片宽度
	 * @param destHeight 目标切片高度
	 */
	public static void cut(String srcImageFile, String descDir, int destWidth, int destHeight)
	{
		try
		{
			Image img;
			ImageFilter cropFilter;
			// 读取源图像
			BufferedImage bi = ImageIO.read(new File(srcImageFile));
			int srcWidth = bi.getHeight(); // 源图宽度
			int srcHeight = bi.getWidth(); // 源图高度
			if (srcWidth > destWidth && srcHeight > destHeight)
			{
				Image image = bi.getScaledInstance(srcWidth, srcHeight,
					Image.SCALE_DEFAULT);
				destWidth = 200; // 切片宽度
				destHeight = 150; // 切片高度
				int cols = 0; // 切片横向数量
				int rows = 0; // 切片纵向数量
				// 计算切片的横向和纵向数量
				if (srcWidth % destWidth == 0)
				{
					cols = srcWidth / destWidth;
				} else
				{
					cols = (int) Math.floor(srcWidth / destWidth) + 1;
				}
				if (srcHeight % destHeight == 0)
				{
					rows = srcHeight / destHeight;
				} else
				{
					rows = (int) Math.floor(srcHeight / destHeight) + 1;
				}
				// 循环建立切片
				// 改进的想法:是否可用多线程加快切割速度
				for (int i = 0; i < rows; i++)
				{
					for (int j = 0; j < cols; j++)
					{
						// 四个参数分别为图像起点坐标和宽高
						// 即: CropImageFilter(int x,int y,int width,int height)
						cropFilter = new CropImageFilter(j * 200, i * 150, destWidth, destHeight);
						img = Toolkit.getDefaultToolkit().createImage(
							new FilteredImageSource(image.getSource(), cropFilter));
						BufferedImage tag = new BufferedImage(destWidth, destHeight, BufferedImage.TYPE_INT_RGB);
						Graphics g = tag.getGraphics();
						g.drawImage(img, 0, 0, null); // 绘制缩小后的图
						g.dispose();
						// 输出为文件
						ImageIO.write(tag, "JPEG", new File(descDir
									+ "pre_map_"
									+ i
									+ "_"
									+ j
									+ ".jpg"));
					}
				}
			}
		} catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	/** */
	/**
	 * 图像类型转换 GIF->JPG GIF->PNG PNG->JPG PNG->GIF(X)
	 */
	public static void convert(String source, String result)
	{
		try
		{
			File f = new File(source);
			f.canRead();
			f.canWrite();
			BufferedImage src = ImageIO.read(f);
			ImageIO.write(src, "JPG", new File(result));
		} catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/** */
	/**
	 * 彩色转为黑白
	 * 
	 * @param source
	 * @param result
	 */
	public static void gray(String source, String result)
	{
		try
		{
			BufferedImage src = ImageIO.read(new File(source));
			ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
			ColorConvertOp op = new ColorConvertOp(cs, null);
			src = op.filter(src, null);
			ImageIO.write(src, "JPEG", new File(result));
		} catch (IOException e)
		{
			e.printStackTrace();
		}
	}

	/**
	 * @function:修改文件名为:原文件名+"_b"
	 * @param resultPath
	 * @return
	 * @author: Guanshengjun 2008-11-28 上午08:50:33
	 */
	public static String returnNewFileName(String resultPath, String suffix)
	{
		String result = "";// 修改后的文件名称
		if (!GenericValidator.isBlankOrNull(resultPath))
		{
			int index = resultPath.lastIndexOf(".");// 获得文件后缀名的位置
			if (index > 0)
			{// 组装改名之后的新文件名称
				result = resultPath.substring(0, index)
							+ suffix
							+ "."
							+ resultPath.substring(index + 1);
				return result;
			}
		}
		return resultPath;
	}

	/**
	 * @function:图片缩放
	 * @param widthL :缩放之后图片宽度
	 * @param s_resultPath :缩放后的图片全路径
	 * @param b_resultPath :原图片
	 * @throws IOException
	 * @author: Guanshengjun 2008-11-28 上午08:44:09
	 */
	public static void changeImageSize(Integer widthL, String s_resultPath, String b_resultPath)
				throws IOException
	{
		try
		{
			BufferedImage src = ImageIO.read(new File(b_resultPath)); // 读入文件
			Integer width = src.getWidth();// 图片原始宽度
			Integer height = src.getHeight();// 图片原始高度
			double w ;// widthL为要缩放的宽度,计算缩放比例
			if(width>=height){
				w=(widthL.intValue()*1.0)/width.intValue();
				width=widthL;
				height=(int) Math.ceil(height*w);
			}else{
				w=(widthL.intValue()*1.0)/height.intValue();
				height=widthL;
				width=(int) Math.ceil(width*w);
			}
			Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);
			BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
			Graphics g = tag.getGraphics();
			g.drawImage(image, 0, 0, null); // 绘制缩小后的图
			g.dispose();
			ImageIO.write(tag, "JPEG", new File(s_resultPath));// 输出到文件流
		} catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	public static void imageToDeal(String imagePath)
	{
		String image_b = "";// 大图片名称
		String nameExt = "";// 文件扩展名
		File file = new File(imagePath);
		if (file.exists())
		{
			if (!file.isDirectory())
			{
				nameExt = file.getName().substring(file.getName().lastIndexOf(".") + 1,
					file.getName().length());
				if (types.indexOf(nameExt.toLowerCase()) != -1)
				{
					String[] xmlPicName = imageNameSuffix(ConstantDefine.PIC_DEAL_SUFFIX);
					if (xmlPicName != null)
					{
						int end = xmlPicName.length / 2;
						String origName = ""; // 原图路径
						String newName = "";// 新生成图的路径
						for (int i = 0; i < end; i++)
						{
							image_b = returnNewFileName(imagePath, xmlPicName[i * 2]); // 获得大图片名称
							File b_file = new File(image_b);
							newName = image_b;
							origName=imagePath;
							// 缩小图片大小:宽,高,上传服务器路径
							try
							{
								changeImageSize(
									Integer.parseInt(xmlPicName[i * 2 + 1]), newName,
									origName);
							} catch (Exception e)
							{
								b_file.renameTo(file);
								e.printStackTrace();
							}
						}
					}
				}
			}
		}
	}

	private static String[] imageNameSuffix(String pathName)
	{
		String name = XmlConfigurationHelper.getParameter(pathName);
		if (GenericValidator.isBlankOrNull(name))
		{
			return null;
		}
		String[] imageName = name.split("\\|");
		return imageName;
	}
}

你可能感兴趣的:(多线程,浏览器,struts,F#,J#)