Flex头像裁剪

这是一个简单的图片裁剪功能,使用的是flex4开发

负责见图的工具类  ImageUtil.as

package common
{
	public class ImageUtil
	{
		import flash.display.Bitmap;
		import flash.display.BitmapData;
		import flash.display.PixelSnapping;
		import flash.geom.Matrix;
		import flash.geom.Rectangle;
		import flash.utils.ByteArray;
		import mx.core.UIComponent;
		import mx.graphics.codec.JPEGEncoder;
		public static  var jpeg:JPEGEncoder = new JPEGEncoder(100);
		public static function cutImage(obj:UIComponent,re:Rectangle):ByteArray
		{
			//矩形为要截取区域  re
			var bmd:BitmapData = new BitmapData(obj.width,obj.height);
			bmd.draw(obj,new Matrix());
			var bm:Bitmap = new Bitmap(bmd,PixelSnapping.ALWAYS,true);
			
			//截取出所选区域的像素集合                        
			var bytearray:ByteArray = bmd.getPixels(re); 
			
			var imgBD:BitmapData = new BitmapData(re.width,re.height);       
			//当前的bytearray.position为最大长度,要设为从0开始读取       
			bytearray.position=0;            
			var fillre:Rectangle = new Rectangle(0,0,re.width,re.height);
			//将截取出的像素集合存在新的bitmapdata里,大小和截取区域一样
			imgBD.setPixels(fillre,bytearray);
			return jpeg.encode(imgBD);
		}
		
	}
}



主文件  CutUpload.mxml
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
			   xmlns:s="library://ns.adobe.com/flex/spark"
			   xmlns:mx="library://ns.adobe.com/flex/mx"
			   width="372" height="425" initialize="init()" xmlns:common="common.*">
	<fx:Script>
		<![CDATA[
			import common.ImageUtil;
			import mx.controls.Alert;
			import mx.core.UIComponent;
			
			
			private var file:FileReference = new FileReference();
			private var urlrequest: URLRequest = new URLRequest();
			
			//图片最大最小宽度、高度
			private var minW:Number = 168;
			private var minH:Number = 168;
			private var maxW:Number = 3000;
			private var maxH:Number = 3000;
			
			//裁剪的图片宽度、高度
			private var fixX:Number = 102;
			private var fixY:Number = 102;
			
			//图片当前的坐标
			private var oldX:Number;
			private var oldY:Number;
			
			
			public function init():void
			{
				Security.allowDomain("*");  
				
				//<embed src="CutUpload.swf" flashVars="url=${url }" allowScriptAccess="always">    
				//网页调用时可以经过flashVars传递参数 ,allowScriptAccess决定了是否可以和javascript交互
				
				//上传url可以经过自定义传参
//				var url:String =  this.parameters.url;
//				urlrequest.url = decodeURI(url);
				
				//或者写死在文件中
				urlrequest.url = "域名+struts2的action";
				//如果要向服务端传递参数
				urlrequest.url = urlrequest.url + "?param=123";
				
				//选择图片事件
				file.addEventListener(Event.SELECT,selectFileHandler);	
				//图片加载完成后事件
				file.addEventListener(Event.COMPLETE,completeFileHandler);
				
				
				var app:Application = this;
				//当按住鼠标左键时,图片随着鼠标移动
				app.addEventListener(MouseEvent.MOUSE_DOWN,function(event:MouseEvent):void
				{
					oldX = event.stageX;
					oldY = event.stageY;
					app.addEventListener(MouseEvent.MOUSE_MOVE,mouseMove);
				});
				//当松开鼠标左键时,删除图片移动事件
				app.addEventListener(MouseEvent.MOUSE_UP,function():void
				{
					app.removeEventListener(MouseEvent.MOUSE_MOVE,mouseMove);
				});
			}
			
			//图片随着鼠标移动
			private function mouseMove(event:MouseEvent):void
			{
				var w:Number = showImg.x-(oldX-event.stageX);
				var h:Number = showImg.y-(oldY-event.stageY);
				showImg.x = w;
				showImg.y = h;
				oldX = event.stageX;
				oldY = event.stageY;
			}
			
			private function showSelectDialog():void
			{
				//过滤非图片文件
				file.browse([
					new FileFilter("Images (*.jpg, *.jpeg, *.gif, *.png)", "*.jpg;*.jpeg;*.gif;*.png")
				]);
			}
			
			//选择图片之后加载
			private function selectFileHandler(e:Event):void
			{
				file.load();
			}
			
			//图片加载完成后
			private function completeFileHandler(e:Event):void
			{
				showImg.source = file.data;
				middle(showImg);
				
			}
			
			//裁剪图片
			private function doCut():void
			{
				if(showImg.source == null)
				{
					return;
				}
				try{
					
					//裁剪
					var re:Rectangle = new Rectangle(fixX-showImg.x,fixY-showImg.y,cut.width,cut.height); 
					var b:ByteArray = ImageUtil.cutImage(showImg,re);
					
					
					urlrequest.data = b;
					var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream");
					urlrequest.method = URLRequestMethod.POST;
					urlrequest.requestHeaders.push(header);
					var loader:URLLoader = new URLLoader();
					loader.load(urlrequest);  
					
					
					loader.addEventListener(Event.COMPLETE,function(e:Event):void{
						//上传完成后的回调函数
						ExternalInterface.call("flexCallBack",loader.data);
					}); 
					
				}catch(error:Error){
					Alert.show("图片超出了裁剪范围");
				}
			}
			
			//放大图片
			private function big(obj:UIComponent):void
			{
				try
				{
					var w:Number = obj.width*0.04;
					var h:Number = obj.height*0.04;
					if((obj.width + w)<=(maxW) && (obj.height + h)<=(maxH))
					{
						obj.width = obj.width+w;
						obj.height = obj.height+h;
						obj.x = obj.x - w/2;
						obj.y = obj.y - w/2;
					}
				} 
				catch(error:Error) 
				{
					
				}
			}
			
			//缩小图片
			private function small(obj:UIComponent):void
			{
				try
				{
					var w:Number = obj.width*0.04;
					var h:Number = obj.height*0.04;
					if((obj.width - w)>=(minW+50) && (obj.height - h)>=(minH+50))
					{
						obj.x = obj.x + w/2;
						obj.y = obj.y + w/2;
						obj.width = obj.width - w;
						obj.height = obj.height - h;
					}
				} 
				catch(error:Error) 
				{
					
				}
				
			}
			
			//图片居中
			private function middle(obj:UIComponent):void
			{
				try
				{
					showImg.x = (this.width-showImg.width)/2;
					showImg.y = (this.height-showImg.height)/2;
				} 
				catch(error:Error) 
				{
					
				}
			}
			
		]]>
	</fx:Script>
	
	<s:Image id="showImg" x="0" y="0" width="400" height="400">
		<s:mouseOver>
			<![CDATA[
			Mouse.cursor = MouseCursor.HAND;//手型控制
			]]>
		</s:mouseOver>
		<s:mouseOut>
			<![CDATA[
			Mouse.cursor = MouseCursor.ARROW;//手型控制
			]]>
		</s:mouseOut>
	</s:Image>
	<mx:VBox x="0" y="0" verticalGap="0" id="coverBox">
		<mx:HBox x="0" y="0" height="48"  horizontalGap="0" backgroundAlpha="1" backgroundColor="#DADADA" borderVisible="true">
			<s:Button width="74" height="48" label="选择" click="showSelectDialog()" useHandCursor="true" buttonMode="true"/>
			<s:Button width="74" height="48" label="上传"  click="doCut()" useHandCursor="true" buttonMode="true"/>
			<s:Button width="74" height="48" label="放大" click="big(showImg)" useHandCursor="true" buttonMode="true"/>
			<s:Button width="74" height="48" label="缩小" click="small(showImg)" useHandCursor="true" buttonMode="true"/>
			<s:Button width="76" height="48" label="居中" click="middle(showImg)" useHandCursor="true" buttonMode="true"/>
		</mx:HBox>
		<mx:HBox width="372" height="58" styleName="fillback">
		</mx:HBox>
		<mx:HBox width="372" height="168" horizontalGap="0">
			<mx:Box width="102" height="168" styleName="fillback">
			</mx:Box>
			<mx:Box width="168" height="168" backgroundAlpha="0" id="cut">
			</mx:Box>
			<mx:Box width="102" height="168" styleName="fillback">
			</mx:Box>
		</mx:HBox>
		<mx:HBox width="372" height="152" styleName="fillback">
		</mx:HBox>
	</mx:VBox>
	<fx:Style>
		@namespace  s "library://ns.adobe.com/flex/spark";
		@namespace  mx "library://ns.adobe.com/flex/mx";
		@namespace  common "common.*";
		.fillback
		{
			backgroundColor:black;
			backgroundAlpha:0.7;
		}
	</fx:Style>
</s:Application>


这里我使用的是struts2作为服务端接收数据
import java.io.File;
import java.io.InputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import com.opensymphony.xwork2.ActionSupport;

public class FlexAction  extends ActionSupport{
	

	/**
	 * 
	 */
	private static final long serialVersionUID = -3543364166243030722L;
	private HttpServletRequest request = ServletActionContext.getRequest();
	private HttpServletResponse response = ServletActionContext.getResponse();
	public static final Integer MAX_SIZE = 1024*1024*2;//允许图片最大尺寸
	
	private String param;
	
	@Action(value = "flexuploadimage")
	public String upload() throws Exception{
		
		System.out.println("param: "+param);
		
		InputStream inputStream = request.getInputStream();
		int formlength = request.getContentLength();
		
		//如果图片大于允许的值
		if(formlength > MAX_SIZE){
			//返回异常信息
			response.getOutputStream().println("自定义返回信息,或者跳转到异常页面");
			return null;
		}
		
		
		byte[] formcontent = new byte[formlength];
		int totalread = 0;
		int nowread = 0;
		while (totalread < formlength) {
			nowread = inputStream.read(formcontent, totalread, formlength);
			totalread += nowread;
		}
		
		//将图片写入本地或者图片服务器
		File file = new File("D:/flex", "t.jpg");
		FileUtils.writeByteArrayToFile(file, formcontent);
		
		return null;
	}

	public String getParam() {
		return param;
	}

	public void setParam(String param) {
		this.param = param;
	}


流程基本上就是这样了,这个UI是模仿QQ空间上传头像的功能,怎奈功力不足,只能这样了,哈哈。


你可能感兴趣的:(Flex头像裁剪)