很多网站都希望用户上传的头像不变形,同时又不希望由公司编辑来进行头像的处理; 
下面这个程序会让你眼前一亮;javascript+java实现用户上传头像并且可按照规定头像长宽比例截图; 
文件1:index.htm  (上传文件页面)
  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> 
 <head> 
     <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> 
     <meta http-equiv="Content-Language" content="en-us" /> 
 <title>upload file</title> 
     <script src="../lib/prototype.js" type="text/javascript"></script>     
      <script src="../lib/scriptaculous.js?load=builder,dragdrop" type="text/javascript"></script> 
     <script src="../cropper.js" type="text/javascript"></script> 
      
      <script type="text/javascript" charset="utf-8">  
          
          function onEndCrop( coords, dimensions )  { 
             $( 'x1' ).value = coords.x1; 
             $( 'y1' ).value = coords.y1; 
             $( 'x2' ).value = coords.x2; 
             $( 'y2' ).value = coords.y2; 
             $( 'width' ).value = dimensions.width; 
             $( 'height' ).value = dimensions.height; 
         } 
          
         // example with a preview of crop results, must have minimumm dimensions 
          function onClickButton() { 
         new Cropper.ImgWithPreview(  
                     'cutimg', 
                       {  
                         minWidth: 200,  
                         minHeight: 120, 
                          ratioDim:  { x: 200, y: 120 }, 
                         displayOnInit: true,  
                         onEndCrop: onEndCrop, 
                         previewWrap: 'previewArea' 
                     }  
                 ) 
         } 
          
          /**//* 
         if( typeof(dump) != 'function' ) { 
             Debug.init(true, '/'); 
              
             function dump( msg ) { 
                 // Debug.raise( msg ); 
             }; 
         } else dump( '---------------------------------------\n' ); 
         */ 
          
     </script> 
     <link rel="stylesheet" type="text/css" href="debug.css" media="all" /> 
      <style type="text/css">  
          label { }{  
             clear: left; 
             margin-left: 50px; 
             float: left; 
             width: 5em; 
         } 
          
          #img { }{ 
             width: 500px; 
             float: left; 
              margin: 20px 0 0 50px; /**//* Just while testing, to make sure we return the correct positions for the image & not the window */ 
         } 
          
          #previewArea { }{ 
             margin: 20px; 0 0 20px; 
             float: left; 
         } 
          
          #results { }{ 
             clear: both; 
         } 
     </style> 
 </head> 
 <body> 
  
 <form action="upload.jsp" id="form1" name="form1" encType="multipart/form-data"  method="post" target="hidden_frame" > 
     <input type="file" id="file" name="file" style="width:450"> 
     <INPUT type="submit" value="上传文件"><font color="red">支持JPG,JPEG,GIF,BMP,SWF,RMVB,RM,AVI文件的上传</font><br /><span id="msg"></span>   <div id="img"></div><div id="previewArea"></div> 
      
     <br> 
                 
     <iframe name='hidden_frame' id="hidden_frame" style='display:none'></iframe> 
 </form> 
 <form action="../CiServlet" method="post" name="form2"> 
 <div id="results"> 
  
             <input type="hidden" name="x1" id="x1" /> 
             <input type="hidden" name="y1" id="y1" /> 
             <input type="hidden" name="x2" id="x2" /> 
             <input type="hidden" name="y2" id="y2" /> 
             <input type="hidden" name="width" id="width" /> 
             <input type="hidden" name="height" id="height" /> 
             <input type="hidden" name="filename" id="filename" /> 
  
     </div><input name="11" type="button" onclick="onClickButton()" value="截图"/> 
     <input type="submit" name="button" id="button" value="保存" /></form> 
  
 </body> 
 </html> 
  
  <script type="text/javascript">  
 function callback(msg,i,path) 
   { 
     document.getElementById("file").outerHTML = document.getElementById("file").outerHTML; 
     document.getElementById("msg").innerHTML = "<font color=red>"+msg+"</font>"; 
      if(i == "1") { 
     insertimg(path); 
     } 
 } 
 function insertimg(path) 
   { 
     document.getElementById("img").innerHTML = "<img src=\"../upload/"+path+"\" alt=\"test image\" id=\"cutimg\" />"; 
     document.getElementById("filename").value = path; 
 } 
 </script>
文件2:upload.jsp(处理文件上传)upload by jspsmartupload
   <% @ page language="java" contentType="text/html; charset=gb2312" %> 
  <% @ page import="com.jspsmart.upload.SmartUpload,java.io.File"%> 
  
  <%  
     //新建一个SmartUpload对象 
     SmartUpload su = new SmartUpload(); 
  
     //上传初始化 
     su.initialize(pageContext); 
  
     // 设定上传限制 
     //1.限制每个上传文件的最大长度。 
     su.setMaxFileSize(10000000); 
  
     //2.限制总上传数据的长度。 
     su.setTotalMaxFileSize(20000000); 
  
     //3.设定允许上传的文件(通过扩展名限制),仅允许doc,txt文件。 
     su.setAllowedFilesList("doc,txt,jpg,rar,mid,waw,mp3,gif"); 
      
     boolean sign = true; 
     String newName = ""; 
     String filepath = ""; 
     String filename = ""; 
      
     //4.设定禁止上传的文件(通过扩展名限制),禁止上传带有exe,bat,jsp,htm,html扩展名的文件和没有扩展名的文件。 
     try { 
         su.setDeniedFilesList("exe,bat,jsp,htm,html"); 
         //上传文件 
         su.upload(); 
         //将上传文件保存到指定目录 
         //su.save("c:\\"); 
         com.jspsmart.upload.File myFile = su.getFiles().getFile(0); 
  
         if (myFile.isMissing()) 
             sign = false; 
         else { 
             java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat( 
                     "yyyyMMddHHmmssms"); 
             java.util.Date currentTime = new java.util.Date(); 
             filepath = application.getRealPath("/")+"upload\\"; //获取当前工程路径 
             if(!new File(filepath).isDirectory()){ 
                  //路径不存在 
                  new File(filepath).mkdir(); 
                  } 
             filename =  formatter.format(currentTime) + "."+ myFile.getFileExt(); 
             newName = filepath + filename; 
             // 
             // 将文件另存 
             myFile.saveAs(newName); 
  
             sign = true; 
         } 
     } catch (Exception e) { 
         e.printStackTrace(); 
         sign = false; 
     } 
     if(sign==true) 
     { 
         out.println("<script>parent.callback('upload file success','1','"+filename+"')</script>"); 
     }else 
     { 
         out.println("<script>parent.callback('upload file error','0','')</script>"); 
     } 
 %> 
 
文件3:CiServlet.java(dopost(),servlet)
  package com.Cropper; 
  
 import java.io.IOException; 
 import javax.servlet.ServletException; 
 import javax.servlet.http.HttpServletRequest; 
 import javax.servlet.http.HttpServletResponse; 
  
  /** *//** 
  * Servlet implementation class for Servlet: CiServlet 
  *  
  */ 
 public class CiServlet extends javax.servlet.http.HttpServlet implements 
          javax.servlet.Servlet  { 
      /**//* 
      * (non-Java-doc) 
      *  
      * @see javax.servlet.http.HttpServlet#HttpServlet() 
      */ 
      public CiServlet()  { 
         super(); 
     } 
  
     protected void doPost(HttpServletRequest request, 
              HttpServletResponse response) throws ServletException, IOException  { 
         // TODO Auto-generated method stub 
         int x = Integer.parseInt(request.getParameter("x1")); 
         int y = Integer.parseInt(request.getParameter("y1")); 
         int w = Integer.parseInt(request.getParameter("width")); 
         int h = Integer.parseInt(request.getParameter("height")); 
         String filename = this.getServletContext().getRealPath("/") 
                 + "upload\\" + request.getParameter("filename"); 
          try  { 
             ImageCut.abscut(filename, x, y, w, h); 
          } catch (Exception e)  { 
             e.printStackTrace(); 
         } 
         System.out.println("截图成功!"); 
     } 
 }
文件4:ImageCut.java(图像处理) 
这里应用以前发表过的一篇关于java图像处理的文章中的一个方法cut(),并稍微改动
  package com.Cropper; 
  
 import java.io.*; 
 import java.awt.*; 
 import java.awt.image.*; 
 import java.awt.Graphics; 
 import javax.imageio.ImageIO; 
  
  public class ImageCut  { 
  
      /** *//** */ 
      /** *//** 
      * 图像切割(改) 
      *  
      * @param srcImageFile 
      *            源图像地址 
      * @param x 
      *            目标切片起点x坐标 
      * @param y 
      *            目标切片起点y坐标 
      * @param destWidth 
      *            目标切片宽度 
      * @param destHeight 
      *            目标切片高度 
      */ 
     public static void abscut(String srcImageFile, int x, int y, int destWidth, 
              int destHeight)  { 
          try  { 
             Image img; 
             ImageFilter cropFilter; 
             // 读取源图像 
             BufferedImage bi = ImageIO.read(new File(srcImageFile)); 
             int srcWidth = bi.getWidth(); // 源图宽度 
             int srcHeight = bi.getHeight(); // 源图高度 
             System.out.println("srcWidth= " + srcWidth + "\tsrcHeight= " 
                     + srcHeight); 
              if (srcWidth >= destWidth && srcHeight >= destHeight)  { 
                 Image image = bi.getScaledInstance(srcWidth, srcHeight, 
                         Image.SCALE_DEFAULT); 
                 // 改进的想法:是否可用多线程加快切割速度 
                 // 四个参数分别为图像起点坐标和宽高 
                 // 即: CropImageFilter(int x,int y,int width,int height) 
                 cropFilter = new CropImageFilter(x, y, 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(srcImageFile)); 
             } 
          } catch (Exception e)  { 
             e.printStackTrace(); 
         } 
     } 
  
      /** *//** */ 
      /** *//** 
      * @param args 
      */ 
      public static void main(String[] args)  { 
         // abscut("upload\\200805151335353535.jpg", 10, 10, 100, 140); 
         abscut("e:/castle.jpg", 10, 11, 500, 281); 
     } 
 }
文件5:web.xml   声明servlet   这个不做介绍
 
最后一些啰嗦的话:javascript这里用到jsCropperUI-1.2.0.zip包;里面还又一些例子;这个东西就去网上找吧
		  
		
	 
	  
	 
	
	    
    
 
				
			  | 
		 
		 
	 | 
	
		
		
			| 
			
			 
随笔:8
文章:23
评论:45
引用:0 
			
			
				
	 |  | 日 | 一 | 二 | 三 | 四 | 五 | 六 | 
|---|
 | 26 | 27 | 28 | 29 | 30 | 31 | 1 |  | 2 | 3 | 4 | 5 | 6 | 7 | 8 |  | 9 | 10 | 11 | 12 | 13 | 14 | 15 |  | 16 | 17 | 18 | 19 | 20 | 21 | 22 |  | 23 | 24 | 25 | 26 | 27 | 28 | 29 |  | 30 | 1 | 2 | 3 | 4 | 5 | 6 |  
  | 
			 
			 
				
			
留言簿(5)
		文章分类(25)
		
				
			
	
最新随笔
搜索
积分与排名
最新评论
	 
			
			 
			
			 | 
		 
		 
	 |