2009-10-20 28 views
2

我試圖顯示一個字節陣列作爲調整大小的圖像。圖像顯示正確,但尺寸已關閉。讓我解釋。從解碼的字節陣列調整圖像大小

首先,我有編碼的圖像數據,所以我需要的圖像數據

// Instantiate decoder 
var decoder:Base64Decoder = new Base64Decoder(); 
// Decode image data 
decoded.decode(picture.data); 
// Export data as a byteArray 
var byteArray:ByteArray = decoder.toByteArray(); 
// Display image 
var img:Image = new Image(); 
img.load(byteArray); 

這工作進行解碼。圖像顯示正確。但是,如果我對圖像(img)高度進行了硬編碼,則調整大小的圖像會正確顯示,但會顯示在包含原始圖像尺寸的框中。

例如,如果原始圖像的高度爲300px,寬度爲200px,img.height屬性設置爲75;高度爲75的調整大小的圖像顯示正確。但是,調整後的圖像顯示在img容器的左上角,該容器仍然設置爲高度爲300px,寬度爲200px。它爲什麼這樣做?什麼是修復?

說明問題的最好方法是將圖像放入VBox中並顯示VBox的邊框。從上面的代碼塊中,如果我更改圖像高度並設置圖像以保持寬高比(默認設置爲true,但爲了完整性,我在此添加)。問題就變得清楚了。

// Display image 
var img:Image = new Image(); 
img.height = 75; // Hardcode image height (thumbnail) 
img.maintainAspectRatio = true; 
img.load(byteArray); 
// Encapsulate the image inside a VBox to illustrate the problem 
var vb:VBox = new VBox(); 
vb.setStyle('borderStyle', 'solid'); 
vb.setStyle('borderColor', 'red'); 
vb.setStyle('borderThickness', 2); 
vb.addChild(img); 

我一直在這個問題上工作幾天,不能拿出解決方案。有任何想法嗎?我錯過了什麼?

回答

1

我使用的解決方法如下:

我創建的事件偵聽器在img顯示對象。然後在img加載後,我手動設置圖像的高度和寬度。我知道我想要的高度(preHeight)是如何硬編碼的。然後我計算寬度並將其設置爲圖像寬度。出於某種原因,我不得不使用explicitHeight和explicitWidth屬性來最終確定尺寸。

我希望這可以幫助別人。

img.addEventListener(FlexEvent.CREATION_COMPLETE, onCreationComplete); 

private function onCreationComplete(event:FlexEvent) : void 
{ 
    img.addEventListener(Event.COMPLETE, onImageLoadComplete); 
} 

private function onImageLoadComplete(event:Event) : void 
{ 
    var image:Image = event.currentTarget as Image; 
    var preHeight:Number = 0; 
    var h:uint = Bitmap(image.content).bitmapData.height; 
    var w:uint = Bitmap(image.content).bitmapData.width; 

    // Check height 
    preHeight = h > 170 ? 170 : h; 
    // Set the width 
    img.explicitWidth = (preHeight * w)/h; 
    img.explicitHeight = preHeight; 
}