flex截图是用mx.graphics.ImageSnapshot类的captureBitmapData方法实现的。给java传码是用Base64进行传码,处理流程如下:
1、获取想要截取区域的像素集合,填充到一个BitmapData中
源码:http://bbs.airia.cn/forum.php?mod=viewthread&tid=12297&highlight=%CD%BC%C6%AC
//获取缩放选择框内的图像
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;
}
2、传输图片内容,使用的Base64的好处:能在java以字符串的形式进行接收
var jpg :JPEGEncoder = new JPEGEncoder();
var jpgByteArray : ByteArray = jpg.encode(getImg());
var Base64:Base64Encoder=new Base64Encoder;//将字符串或 ByteArray 编码为 Base64 编码的字符串。
Base64.encodeBytes(jpgByteArray)
var imageStr:String=Base64.toString();//输出为字符串
// Alert.show(""+imageStr);
xxxProxy.load(imageStr);
xxx Proxy是PureMVC中的Proxy的一个实例。
http://blog.flexexamples.com/2008/03/17/displaying-an-image-saved-as-a-base64-encoded-string-in-flex-3/可以把Alert弹出的字符串放到logo.txt进行验证
3、java端接收字符串进行处理
public ActionForward exportImg(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception
{
Map<String, Object> rsMap = new HashMap<String, Object>();
try {
String imageStr = request.getParameter("imageStr");
String id = request.getParameter("id");
// String imagename = System.currentTimeMillis() + ".png";
BASE64Decoder decoder = new BASE64Decoder();
//Base64解码
byte[] b = decoder.decodeBuffer(imageStr);
for(int i=0;i<b.length;++i)
{
if(b[i]<0)
{//调整异常数据
// System.out.println("11"+b[i]);
b[i]+=256;
// System.out.println("22"+b[i]);
}
}
String imagename = id + ".png";//
response.setContentType("image/jpg");
response.setContentType("application/ms-excel");
response.setHeader("Content-Disposition", "attachment;filename="
+ new String(imagename.getBytes(), "iso-8859-1"));
String imgView = "soc/Resources/Thumbnail/deployexport/" + imagename;
File imgFile = new File(path + imgView);
FileOutputStream fos = new FileOutputStream(imgFile);
fos.write(b);
fos.flush();
fos.close();
//
}
catch (Exception e) {
}
return null;
4、存在问题:
(1) 不清晰 尤其是存在文字时 有锯齿
(2) 控制截取区域的控件不能超过屏幕大小,否报错
(3) 要是存在java保存的图片背景是黑色的问题,应该先检查下Flex截取图片的背景。 若问题在Flex,则要检查Canvas的背景是否为空,或者默认值为0x000000。若存在不 能给Canvas的背景赋值,可以结合背景透明度进行设置,也就是给背景赋值,透明度为0或者很小的数。