flex将一副图片转化成二进制,然后再转化成bmp

As包:

package com.pag
{
 import flash.display.Bitmap;
 import flash.display.BitmapData;
 import flash.geom.Rectangle;
 import flash.utils.ByteArray;
 import mx.controls.Alert;
 
 public class BitmapBytes
 {
  public function BitmapBytes()
  {
   super();
  }
  
  public static function BitmapDataToByteArray(target:Bitmap):ByteArray{
   var imageWidth:uint = target.width;
   var imageHeigh:uint = target.height;
   var srcBmp:BitmapData = new BitmapData(imageWidth,imageHeigh);
   srcBmp.draw(target);
   var pixels:ByteArray = srcBmp.getPixels(new Rectangle(0,0,imageWidth,imageHeigh));
   pixels.writeShort(imageHeigh);
   pixels.writeShort(imageWidth);
   Alert.show(""+pixels);
   return pixels;
  }
  
  public static function ByteArrayToBitmap(byArr:ByteArray):Bitmap{
   if(byArr == null)
    return null;
   var bmd:ByteArray = byArr;
   bmd.position = bmd.length - 2;
   var imageWidth:int = bmd.readShort();
   bmd.position = bmd.length - 4;
   var imageHeight:int = bmd.readShort();
   var copyBmp:BitmapData = new BitmapData(imageWidth,imageHeight,true);
   bmd.position = 0;
   for(var i:uint=0;i<imageHeight;i++){
    for(var j:uint=0;j<imageWidth;j++){
     copyBmp.setPixel(j,i,bmd.readUnsignedInt());
    }
   }
   var bmp:Bitmap = new Bitmap(copyBmp);
   return bmp;
  }

 }
}

 

 

mxml文件:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="init();">
 <mx:Script>
  <![CDATA[
   import com.pag.BitmapBytes;
   private static var bmp:Bitmap;
   private var loader:Loader;
   private function init():void{
//    var img1:Image = new Image();
//    img1.source = "img/3.jpg";
//    var byArr:ByteArray = BitmapBytes.BitmapDataToByteArray(img1);
//    bmp = BitmapBytes.ByteArrayToBitmap(byArr); 
    loader = new Loader();
    var request:URLRequest = new URLRequest("img/3.jpg");
    loader.contentLoaderInfo.addEventListener(Event.COMPLETE,getBmpInfo);
    loader.load(request);
   }
   
   private function getBmpInfo(event:Event):void{
    var bitmp:Bitmap = (Bitmap)(loader.content);
    var byArr:ByteArray = BitmapBytes.BitmapDataToByteArray(bitmp);
    bmp = BitmapBytes.ByteArrayToBitmap(byArr);
    trace(bmp);   
//    img2.source = bmp;
//    img3.source = bmp;      
   }
   
   
   private function changTo():void{
    trace(bmp);
    img2.source = bmp;
   }
   
   private function changTo2():void{
    trace(bmp);
    img3.source = bmp;
   }
  ]]>
 </mx:Script>
 <mx:Image id="img2"  x="63"/>
 <mx:Button click="changTo();" x="0" y="0" label="Button"/>
 <mx:Button click="changTo2();" x="471" y="10" label="Button"/>
 <mx:Image id="img3"  x="535" y="2"/>
</mx:Application>

你可能感兴趣的:(flex将一副图片转化成二进制,然后再转化成bmp)