隨筆-19  評論-128  文章-1  trackbacks-0

          功能:在線拍照
          簡介:用flex與java結合實現在線拍照
          需求:為了滿足希望通過攝像頭拍照的圖片,然后通過服務器來展示需要
          效果:
                      后臺: 

                      前臺:


          實現代碼:
          flex:

          <?xml version="1.0" encoding="utf-8"?>
          <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" width="388" height="222" creationComplete="initApp()" backgroundColor="#A6C9E2">
               
          <mx:Style>
                   Alert{font-size:12px;}
               
          </mx:Style>
               
          <mx:Script>
                   
          <![CDATA[
                       import mx.events.CloseEvent;
                       import mx.rpc.events.FaultEvent;
                       import mx.rpc.events.ResultEvent;
                       import mx.controls.Alert;
                       import mx.core.Application;
                      
                       private static const DEFAULT_CAMERA_WIDTH:Number = 160; //攝像頭顯示寬度
                       private static const DEFAULT_CAMERA_HEIGHT:Number = 120; //攝像頭顯示高度
                       private var DEFAULT_WEBSERVICE_URL:String = ""; //WebService地址
                       private var str:String;
                      
                       private var m_camera:Camera; //定義一個攝像頭
                       private var m_localVideo:Video; //定義一個本地視頻
                       private var m_pictureBitmapData:BitmapData //定義視頻截圖
                       [Bindable]
                       private var m_pictureData:String;
                      
                       private function initApp():void
                       {
                           t_btn_Shooting.enabled = false;
                           t_ban_Save.enabled = false;
                           initCamera();
                           DEFAULT_WEBSERVICE_URL = Application.application.parameters.contextPath+"/onLineTakePhotoServlet";
                           t_ws_SavePicture.url=DEFAULT_WEBSERVICE_URL;
                       }
                      
                       //初始化攝像頭
                       private function initCamera():void
                       {
                           m_camera = Camera.getCamera();
                           if(m_camera != null)
                           {
                               m_camera.addEventListener(StatusEvent.STATUS,__onCameraStatusHandler);
                              
                               m_camera.setMode(DEFAULT_CAMERA_WIDTH,DEFAULT_CAMERA_HEIGHT,30);
                               m_localVideo = new Video();
                               m_localVideo.width = DEFAULT_CAMERA_WIDTH;
                               m_localVideo.height = DEFAULT_CAMERA_HEIGHT;
                               m_localVideo.attachCamera(m_camera);
                               t_vd_Video.addChild(m_localVideo);
                           }
                           else
                           {
                               Alert.show("沒有找到攝像頭,是否重新查找。","提示:",Alert.OK|Alert.NO,this,__InitCamera);
                               return;
                           }
                       }
                      
                       //拍照按鈕事件,進行視頻截圖
                       private function SnapshotPicture():void
                       {
                           m_pictureBitmapData = new BitmapData(DEFAULT_CAMERA_WIDTH,DEFAULT_CAMERA_HEIGHT);
                           m_pictureBitmapData.draw(t_vd_Video,new Matrix());
                          
                           var m_pictureBitmap:Bitmap = new Bitmap(m_pictureBitmapData);
                           t_img_Picture.addChild(m_pictureBitmap);
                          
                           t_panel_Picture.visible = true;
                           t_ban_Save.enabled = true;
                       }
                      
                       //保存按鈕事件,保存視頻截圖
                       //通過WebService保存
                       private function SavePicture():void
                       {
                           m_pictureData = "";
                           for(var i:int = 0; i < DEFAULT_CAMERA_WIDTH; i++)
                           {
                               for(var j:int = 0; j < DEFAULT_CAMERA_HEIGHT; j++)
                               {
                                   if(m_pictureData.length > 0)
                                   {
                                       m_pictureData += "," + m_pictureBitmapData.getPixel32(i,j).toString();
                                   }
                                   else
                                   {
                                       m_pictureData = m_pictureBitmapData.getPixel32(i,j).toString();
                                   }
                               }
                           }
                           
                           var params:URLVariables = new URLVariables();
               params.width = DEFAULT_CAMERA_WIDTH;
               params.height = DEFAULT_CAMERA_HEIGHT;
               params.bitmap_data = m_pictureData;
               t_ws_SavePicture.send(params);
                       }
                      
                       //檢測攝像頭權限事件
                       private function __onCameraStatusHandler(event:StatusEvent):void
                       {
                           if(!m_camera.muted)
                           {
                               t_btn_Shooting.enabled = true;
                           }
                           else
                           {
                               Alert.show("無法鏈接到活動攝像頭,是否重新檢測。","提示:",Alert.OK|Alert.NO,this,__InitCamera);
                           }
                           m_camera.removeEventListener(StatusEvent.STATUS,__onCameraStatusHandler);
                       }
                      
                       //當攝像頭不存在,或連接不正常時重新獲取
                       private function __InitCamera(event:CloseEvent):void
                       {
                           if(event.detail == Alert.OK)
                           {
                               initApp();
                           }
                       }
                      
                       //WebService保存圖片成功事件
                       private function __onSavePictureResult(event:ResultEvent):void
                       {
                           //trace(event.result);
                           if(event.result.toString() != "保存失敗")
                           {
                             str = event.result.toString();
                             
                               Alert.show("保存成功,是否關閉窗口?","提示",3,this,__onAlertCloseHandler);
                           }
                           else
                           {
                               Alert.show(event.result.toString(),"提示",Alert.OK);
                           }
                       }
                      
                       //連接WebService失敗事件
                       private function __onSavePictureFault(event:FaultEvent):void
                       {
                           //Alert.show(event.fault.toString(),"提示",Alert.OK);
                           Alert.show("連接服務器失敗。","提示",Alert.OK);
                       }
                      
                       //保存圖片成功后的彈出窗口確認事件
                       private function __onAlertCloseHandler(event:CloseEvent):void
                       {
                           if(event.detail == Alert.YES)
                           {
                              ExternalInterface.call("setValueToField",str);
                           }
                       }
                   
          ]]>
               
          </mx:Script>
               
          <mx:HTTPService id="t_ws_SavePicture" showBusyCursor="true" method="POST" useProxy="false" result="__onSavePictureResult(event)" fault="__onSavePictureFault(event)"/>
               
          <mx:Panel x="10" y="10" width="180" height="200" layout="absolute" title="視頻拍照" fontSize="12">
                   
          <mx:VideoDisplay id="t_vd_Video" width="160" height="120"/>
                   
          <mx:ControlBar horizontalAlign="right">
                       
          <mx:Button id="t_btn_Shooting" label="拍照" click="SnapshotPicture()"/>
                   
          </mx:ControlBar>
               
          </mx:Panel>
               
          <mx:Panel id="t_panel_Picture" x="198" y="10" width="180" height="200" layout="absolute" title="拍照圖片" fontSize="12" visible="false">
                   
          <mx:Image id="t_img_Picture" x="0" y="0" width="160" height="120"/>
                   
          <mx:ControlBar   horizontalAlign="right">
                       
          <mx:Button id="t_ban_Save" label="保存" click="SavePicture()" />
                   
          </mx:ControlBar>
               
          </mx:Panel>
          </mx:Application>



          java:

          package cn.myapps.core.onlinetakephoto;

          import java.awt.Color;
          import java.awt.image.BufferedImage;
          import java.io.ByteArrayOutputStream;
          import java.io.DataOutputStream;
          import java.io.File;
          import java.io.FileOutputStream;
          import java.io.IOException;

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

          import cn.myapps.constans.Environment;
          import cn.myapps.util.sequence.Sequence;

          /**
           * Servlet implementation class onLineTakePhotoServlet
           
          */
          public class onLineTakePhotoServlet extends HttpServlet {
           
          private static final long serialVersionUID = 1L;
              
           
          private Environment env = Environment.getInstance();
           
           
          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 {
            response.setContentType(
          "text/html;charset=UTF-8");   
                  response.setHeader(
          "Pragma""No-cache");   
                  response.setHeader(
          "Cache-Control""no-cache");   
                  response.setDateHeader(
          "Expires"0);   
            
                  String bitmap_data 
          = request.getParameter("bitmap_data");   
                  
          int width = Integer.parseInt(request.getParameter("width"));   
                  
          int height = Integer.parseInt(request.getParameter("height"));   
                  BufferedImage img 
          = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);   
            
          try {   
                      
          int w = width;   
                      
          int h = height;   
                      
          int[] pixels = new int[w * h];   
                      String[] m_tempPics 
          = bitmap_data.split(",");   
                      
          for (int x = 0; x < w; x++) {   
                          
          for (int y = 0; y < h; y++) {   
                              Long pic_argb 
          = Long.parseLong(m_tempPics[x * h + y]);   
                              
          int a = (int) (pic_argb >> 24 & 0xFF);   
                              
          int r = (int) (pic_argb >> 16 & 0xFF);   
                              
          int g = (int) (pic_argb >> 8 & 0xFF);   
                              
          int b = (int) (pic_argb & 0xFF);   
                              pixels[y 
          * w + x] = new Color(r, g, b, a).getRGB();   
                          }   
                      }   
                      img.setRGB(
          00, w, h, pixels, 0, w);   
                      img.flush();   
                      ByteArrayOutputStream bao 
          = new ByteArrayOutputStream();   
                      ImageIO.write(img, 
          "jpg", bao);   
                      
          byte[] data = bao.toByteArray();  
                      String filePath 
          = env.getRealPath("/uploads/photo");
                      
          //判斷路徑是否存在,若不存在則創建路徑
                      File upDir = new File(filePath);
                      
          if (!upDir.exists())
                      {
                          upDir.mkdir();
                      }
                      
          //生成隨機文件名
                      String saveName = Sequence.getSequence();
                      String fileName 
          = saveName + ".jpg";
                      
          //寫圖片
                      File f = new File(filePath+"\\" + fileName);
                DataOutputStream dos 
          = new DataOutputStream(new FileOutputStream(f));
                dos.write(data);
                dos.flush();
                dos.close();
                response.setContentType(
          "text/xml");   
                      response.getWriter().write(
          "/uploads/photo/" + fileName);   
                  }
                  
          catch(Exception ex)
                  {
                   response.setContentType(
          "text/xml");   
                      response.getWriter().write(
          "保存失敗");   
                  }
           }

          }

           


          源碼:/Files/obpm/onlinetakephoto.rar

           原創人員:Denny

          posted on 2010-08-29 21:52 obpm 閱讀(5518) 評論(5)  編輯  收藏 所屬分類: 表單 、控件 、Flex

          評論:
          # re: Flex在線拍照功能(原創)[未登錄] 2010-08-30 11:14 | magicma
          不錯,能不能提供源碼研究一下,我的郵箱:maw@nci.com.cn  回復  更多評論
            
          # re: Flex在線拍照功能(原創) 2010-08-30 22:04 | ol
          @magicma
          http://www.open-lib.com/Lib/764.jsp

          有現場的開源東西可用呢。。。  回復  更多評論
            
          # re: Flex在線拍照功能(附源碼) 2011-06-17 16:04 | caper
          caopu520@126.com  回復  更多評論
            
          # re: Flex在線拍照功能(附源碼) 2011-06-27 16:37 | tgy
          m_camera.addEventListener(StatusEvent.STATUS,__onCameraStatusHandler);
          請問這第兩個參數分別代表什么?為什么我的第二個參數報錯了呢?  回復  更多評論
            
          # re: Flex在線拍照功能(附源碼) 2014-04-13 10:52 | 123yedddd
          請問flex里面那段 <![CDATA[是注釋掉的嗎? 為什么改 Alert.show("連接服務器失敗。","提示",Alert.OK); 沒有用? 哪段是連接后臺。圖片保存到哪了。。  回復  更多評論
            

          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 昌吉市| 南雄市| 东城区| 全南县| 安泽县| 芦山县| 西林县| 乌什县| 南投县| 大田县| 武宁县| 乐业县| 河池市| 平潭县| 锡林郭勒盟| 邢台市| 遂宁市| 泗水县| 万州区| 那曲县| 肇州县| 色达县| 扎鲁特旗| 隆尧县| 新田县| 枞阳县| 珠海市| 丰原市| 界首市| 湖南省| 马鞍山市| 开远市| 勐海县| 景洪市| 嵩明县| 化隆| 新平| 柏乡县| 陇川县| 大渡口区| 郓城县|