隨筆-19  評論-128  文章-1  trackbacks-0
          圖片剪切功能:

          效果圖:






          flex代碼:

           

          <?xml version="1.0" encoding="utf-8"?>
          <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" initialize="init()" xmlns:local="astion.*">
           
          <mx:Script>
            
          <![CDATA[
             import mx.controls.Image;
             import mx.graphics.ImageSnapshot;
             import flash.net.FileReference;
             import mx.graphics.codec.JPEGEncoder;
             import mx.managers.PopUpManager;
             import mx.containers.TitleWindow;
             import mx.controls.Alert;
             import mx.events.CloseEvent;
             import mx.core.IFlexDisplayObject;
             import mx.utils.*;
             import mx.core.Application;
             import astion.Dot;
             import astion.ScaleBox;
             
             public static const LINE_WIDTH:Number = 1;//縮放邊框寬度
             private var file:FileReference;
             public var IMAGE_URL:String="http://localhost:8080/cutPicuter/aa/aa.jpg";
             private var loader:Loader;
             private var bmp:Bitmap;
                      private var stream:URLStream;
                      public var realPath:String="D:\myWorkSpace\cutPicuter\WebRoot\aa\aa.jpg";
             
             //初始化數據
             private function init():void{
              this.loader = new Loader();
                          this.stream = new URLStream();
                          this.loader.contentLoaderInfo.addEventListener(Event.COMPLETE,this.onComplete);
                          this.loader.load(new URLRequest(encodeURI(this.IMAGE_URL)));//解決中文亂碼
                          this.stream.load(new URLRequest(encodeURI(this.IMAGE_URL)));
                          this.stream.addEventListener(Event.COMPLETE,this.onLoaded);
             }
             private function onLoaded(e:Event):void
                      {                                
                          var bytearray:ByteArray = new ByteArray();    
                          this.stream.readBytes(bytearray);
                          
                          if(this.stream.connected)
                              this.stream.close();
                              
                          this.loader.loadBytes(bytearray);
                      }
                      private function onComplete(e:Event):void
                      {
                          try
                          {
                              this.bmp = this.loader.content as Bitmap;
                              var showImage:Image= new Image();
                              showImage.source=this.loader.content;
                              canvas.addChild(showImage);
                              canvas.setChildIndex(box,1);
                              canvas.setChildIndex(showImage,0);
                          }
                          catch(e:Error)
                          {
                              
                          }
                      }
             
             //截圖,顯示縮放選擇框
             private function doCapture():void{
              box.x = 100;
              box.y = 100;
              box.visible = true;
             }
             
             //獲取縮放選擇框內的圖像
             private function getImg():BitmapData{
              //截取整個區域
              box.scaleEnable = false;
              var bmp:BitmapData = ImageSnapshot.captureBitmapData(canvas);
              box.scaleEnable = true;
              
              //矩形為要截取區域                
                          var re:Rectangle = new Rectangle(box.x+LINE_WIDTH,box.y+LINE_WIDTH,box.boxWidth-LINE_WIDTH,box.boxHeight-LINE_WIDTH); 
                          var bytearray:ByteArray = new ByteArray();   
                          //截取出所選區域的像素集合                        
                          bytearray = bmp.getPixels(re); 
                          
                          
                          var imgBD:BitmapData = new BitmapData(box.boxWidth-LINE_WIDTH,box.boxHeight-LINE_WIDTH);       
                          //當前的bytearray.position為最大長度,要設為從0開始讀取       
                          bytearray.position=0;            
                          var fillre:Rectangle = new Rectangle(0,0,box.boxWidth-LINE_WIDTH,box.boxHeight-LINE_WIDTH);
                          //將截取出的像素集合存在新的bitmapdata里,大小和截取區域一樣
                          imgBD.setPixels(fillre,bytearray);
                          
                          return imgBD;
             }
             
             //預覽圖片
             private function doScan():void{
              var t:TitleWindow = new TitleWindow();
              t.showCloseButton=true;
              t.addEventListener(CloseEvent.CLOSE,closeWindow);
              t.width = box.boxWidth+t.getStyle("borderThickness");
              t.height =box.boxHeight+t.getStyle("borderThickness")+t.getStyle("headerHeight");
              var img:Image = new Image();
              img.width = box.boxWidth;
              img.height = box.boxHeight; 
              img.source = new Bitmap(getImg());
              t.addChild(img);
              PopUpManager.addPopUp(t,this,true);
              PopUpManager.centerPopUp(t);
             }
             
             private function closeWindow(e:CloseEvent):void{            
                          var t:TitleWindow = e.currentTarget as TitleWindow;                    
                          PopUpManager.removePopUp(t);                
                      }
                      
                      //保存圖片到本地
             private function downloadPicture():void{
              file=new FileReference();
              file.addEventListener(Event.COMPLETE,downloadComplete);
              file.save(new JPEGEncoder(80).encode(getImg()),"default.jpg");
             }
             
             private function downloadComplete(event:Event):void{
              Alert.show("成功保存圖片到本地!","提示");
             }
             
             //保存圖片到服務器即覆蓋原來的圖片
             private function save():void{
              Alert.show("是否保存剪切圖片?","提示",3, this, function(event:CloseEvent):void {
                    if (event.detail==Alert.YES){
                     var request:URLRequest = new URLRequest("http://localhost:8080/cutPicuter/servlet/FileManagerSaveFileServlet?realPath="+encodeURIComponent(StringUtil.trim(realPath)));
               request.method=URLRequestMethod.POST;
               request.contentType = "application/octet-stream";
               request.data = new JPEGEncoder(80).encode(getImg());
               var loader:URLLoader = new URLLoader();
               loader.load(request);
               loader.addEventListener(Event.COMPLETE,saveResult);

                    }});
             }
             
             private function saveResult(event:Event):void{
              Application.application.reLoadFolderFiles(realPath.substr(0,realPath.lastIndexOf("\\")));
              Alert.show("保存剪切圖片成功","提示");
             }
            
          ]]>
           
          </mx:Script>
           
          <mx:HBox x="0" y="0">
                  
          <mx:LinkButton label="剪裁" click="doCapture();" icon="@Embed('assets/cut.png')"/>
                  
          <mx:LinkButton label="預覽" click="doScan();" icon="@Embed('assets/ok.png')"/>
                  
          <mx:VRule height="22"/>
                  
          <mx:LinkButton label="保存"  click="save()"  icon="@Embed('assets/save.png')"/>
                  
          <mx:LinkButton label="另存為" click="downloadPicture();" icon="@Embed('assets/saveAs.png')"/>
              
          </mx:HBox>
           
          <mx:Canvas id="canvas" y="23" x="1">
           
          <local:ScaleBox id="box" visible="false" y="0" x="0" width="100" height="100"/>
           
          </mx:Canvas>
          </mx:Application>



          java代碼:

           

          package com;


          import java.io.DataOutputStream;
          import java.io.File;
          import java.io.FileOutputStream;
          import java.io.IOException;
          import java.io.InputStream;

          import javax.servlet.ServletException;
          import javax.servlet.http.HttpServlet;
          import javax.servlet.http.HttpServletRequest;
          import javax.servlet.http.HttpServletResponse;

          /**
           * Servlet implementation class FileManagerSaveFileServlet
           
          */
          public class FileManagerSaveFileServlet extends HttpServlet {
           
           
          private int len=0;//處理流
           private int mm=0;//重命名
           private String fileName="";//文件原名
           private String extName="";//文件擴展名
           private String tempFileName="";//文件名加擴展名
           
           
          public void doGet(HttpServletRequest request, HttpServletResponse response)    
           
          throws ServletException, IOException {    
           processRequest(request, response);    
           }    
             
           
          public void doPost(HttpServletRequest request, HttpServletResponse response)    
            
          throws ServletException, IOException {    
           processRequest(request, response);    
           }    
           
           
          public void processRequest(HttpServletRequest request, HttpServletResponse response)

              
          throws ServletException, IOException {
            request.setCharacterEncoding(
          "utf-8");
            String realPath
          =request.getParameter("realPath");
            
          //System.out.println("FMSFS-->realPath:"+realPath);
            response.setContentType("application/octet-stream");
            InputStream is 
          = request.getInputStream();
            
          try {
            
          int size = 0;
            
          byte[] tmp = new byte[100000];
            
            tempFileName
          =realPath.substring(realPath.lastIndexOf("\\")+1);//切割獲得文件名加擴展名
            fileName=tempFileName.substring(0,tempFileName.lastIndexOf("."));//切割獲得文件名
            
          //確保獲得真實的文件名如:1(1)可以獲得真實為1,
            if(fileName.indexOf("(")!=-1){
             fileName
          =fileName.substring(0,fileName.indexOf("("));
            }
            
            extName
          =tempFileName.substring(tempFileName.lastIndexOf("."));//切割獲得擴展名
            
            
          //調用遞歸方法
            fileName+=reNameFile(realPath.substring(0,realPath.lastIndexOf("\\")+1),fileName,extName);
            
          // 創建一個文件夾用來保存發過來的圖片;
            File f = new File(realPath.substring(0,realPath.lastIndexOf("\\")+1)+fileName+extName);
            DataOutputStream dos 
          = new DataOutputStream(new FileOutputStream(f));
            
          while ((len = is.read(tmp)) != -1) {
            dos.write(tmp, 
          0, len);
            size 
          += len;
            }
            dos.flush();
            dos.close();
            } 
          catch (IOException e) {
            e.printStackTrace();
            }
           }
           
           
          //遞歸來重命名文件名
           String str="";
           
          public String reNameFile(String realPath,String filename,String extName){
            File file 
          =new File(realPath+"\\"+filename+extName);
            str
          ="";
                  
          if(file.exists()){
                   mm
          ++;
                   str
          ="_"+mm;
                   reNameFile(realPath,fileName
          +str,extName);
                  }
          else{
                   
          if(mm!=0){
                str
          ="_"+mm;
                   }
                  }
            
          return str;
           }
          }

           


           

          源碼: flex圖片剪切示例


          原創人員:Denny

          posted on 2010-09-01 09:55 obpm 閱讀(8608) 評論(6)  編輯  收藏 所屬分類: 控件Flex

          評論:
          # re: flex圖片剪切示例--預覽、保存到本地、保存到服務器(附源碼) 2010-09-09 21:15 | fk01
          請問樓主,你這個拖動的時候選擇框怎么控制在的范圍啊  回復  更多評論
            
          # re: flex圖片剪切示例--預覽、保存到本地、保存到服務器(附源碼) 2010-09-10 16:02 | axsz4251
          很棒的學習資料,感謝提供!  回復  更多評論
            
          # re: flex圖片剪切示例--預覽、保存到本地、保存到服務器(附源碼) 2011-10-25 16:33 | mymoon
          前臺的Application.application.reLoadFolderFiles方法已經被官方屏蔽了,不能用了,還有別的方法嗎?  回復  更多評論
            
          # re: flex圖片剪切示例--預覽、保存到本地、保存到服務器(附源碼)[未登錄] 2011-11-09 11:17 | tom
          樓主,是不是還少個類啊 local:ScaleBox   回復  更多評論
            
          # re: flex圖片剪切示例--預覽、保存到本地、保存到服務器(附源碼) 2011-11-18 09:33 | 慕容若雪
          是不是少點東西啊,樓主  回復  更多評論
            
          # re: flex圖片剪切示例--預覽、保存到本地、保存到服務器(附源碼) 2011-11-18 09:34 | 慕容若雪
          加我QQ:119449201

          還有些不明白的地方想向你請教  回復  更多評論
            
          主站蜘蛛池模板: 楚雄市| 双江| 封丘县| 广元市| 佛教| 沅陵县| 石河子市| 锡林浩特市| 永丰县| 汉川市| 卢湾区| 柘荣县| 彰武县| 台中市| 神农架林区| 梨树县| 敦煌市| 长泰县| 萨嘎县| 福安市| 长宁县| 吴桥县| 平乐县| 车致| 南阳市| 罗定市| 河北省| 河源市| 新河县| 垦利县| 从化市| 罗定市| 江陵县| 衡东县| 河南省| 公主岭市| 古丈县| 鹰潭市| 高尔夫| 洛扎县| 宿州市|