flex图片剪切示例--预览、保存到本地、保存到服务器(附源码)

来源:互联网 发布:螺纹铣刀m32怎么编程 编辑:程序博客网 时间:2024/06/05 22:33
flex图片剪切示例--预览、保存到本地、保存到服务器(附源码)
图片剪切功能:

效果图:






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;
 }
}

原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 苹果手机卡不紧怎么办 华为平板字体小怎么办 充电口有灰尘怎么办 钥匙孔被异物堵住怎么办 音响线接触不良怎么办 耳塞孔接触不良怎么办 右耳机接触不好怎么办 华为手机密码忘怎么办 三星s6声音小怎么办 耳麦一边没声音怎么办 手机指环扣掉了怎么办 小米5跑流量怎么办 手机自动跑流量怎么办 华为p9主板漏电怎么办 三星s7内存不够怎么办 华为p9b399系统耗电怎么办 手机太卡应该怎么办 京东买东西次品怎么办 华为mate8手机用久卡顿怎么办 电话本突然丢了怎么办 去香港一天流量怎么办 华为声音没了怎么办 手机usb连不上电脑怎么办 华为说话声音小怎么办 手机帧率不稳定怎么办? 施华洛世奇项链折了怎么办 香港买首饰过关怎么办 香港花旗参被骗怎么办 香港过关珠宝盒怎么办 香港psn注册不起怎么办 魅族手机单声道怎么办 m1note屏幕反了怎么办 桌面推荐删了怎么办 vr一体机卡死了怎么办 荣耀10费电怎么办 魅蓝s6吃鸡卡顿怎么办 农村网络信号差怎么办 手机点击不明链接怎么办 华为手机wifi慢怎么办 浏览器打不开显示内存不足怎么办 华为电脑黑屏了怎么办