转:http://www.blogjava.net/obpm/archive/2010/09/01/330501.html
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; } }