flex下显示数据库的图片可以借助于webservice,然后将得到的二进制数据显示在图片中。有一个比较麻烦的问题是flex中的图片没有类似的loadBytes(加载二进制)的方法,必须进行扩展。在网上找到了一个ByteArrayImage的类,基本可以满足要求,但是在动态设置宽度,以及是/否平铺上存在问题,于是进行了改造。 另外,c#中存入数据库中的图片类型为 byte[] , 而flex中为ByteArray,这一点也需要注意。
Code:
package com
{
import flash.display.Loader;
import flash.events.Event;
import flash.system.LoaderContext;
import flash.utils.ByteArray;
import mx.controls.Image;
public class ByteArrayImage extends mx.controls.Image
{
private var _loader:Loader = new Loader();
private var _bFillUp:Boolean = false; //是/否平铺
//public function Image():void {}
override protected function createChildren():void
{
addChild(_loader);
}
public function get bFillUp():Boolean{
return _bFillUp;
}
public function set bFillUp(value:Boolean):void{
this._bFillUp = value;
}
public function loadBytes(bytes:ByteArray,context:LoaderContext=null):void
{
_loader.loadBytes(bytes, context);
_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onBytesLoaded);
}
private function onBytesLoaded(e:Event):void
{
if(_bFillUp)
{
_loader.width = this.width;
_loader.height = this.height;
}
// this.width = e.target.width;
// this.height = e.target.height;
}
public function SetWidth(newWidth:Number):void{
this.width = newWidth;
this._loader.width = this.width;
}
}
}
以下为webservice相关代码;
private function LoadVideoHead():void{
var service:WebService = new WebService();
service.loadWSDL(strWebSrvPath);
service.addEventListener(ResultEvent.RESULT,onLoadVideoHeadResult);
service.addEventListener(FaultEvent.FAULT,onLoadVideoHeadFault);
service.GetVideoHeadByMediaID(nMediaID);
}
private function onLoadVideoHeadResult(evt:ResultEvent):void
{
var imgD:ByteArrayImage = null;
if(evt.result.MediaID>0)
{
var objVideoHead:Object = evt.result;
var arrImage:ByteArray = objVideoHead.Content as ByteArray ; // byte[] To ByteArray ? //数据库中图片二进制形式
imgD = new ByteArrayImage();
imgD.bFillUp = true; //平铺
imgD.width = bxDVideo.width-2*nBorderThickness;
imgD.height = bxDVideo.height-2*nBorderThickness;
imgD.x = nBorderThickness;
imgD.y = nBorderThickness;
imgD.loadBytes(arrImage);
display_d.addChild(imgD);
}
}