Resize image from decoded ByteArray

I am trying to display a bytearray as a modified image. The image is displayed correctly, but the size is not set. Let me explain.

First I have the image data encoded so I need to decode the image data

// 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);

      

It works. The image is displayed correctly. However, if I hard-code the height of the image (img), the resized image is displayed correctly, but inside the box with the original dimensions of the image.

For example, if the original image is 300 pixels high and 200 pixels wide, and the img.height property is set to 75; the image at an increased height of 75 is shown correctly. But the modified image is displayed in the upper left corner of the img container, which is still set to 300px high and 200px wide. Why is this so? And what is a fix?

The best way to illustrate the problem is to place the image inside the VBox and show the borders of the VBox. From the code above, if I change the height of the image and set the image to keep the aspect ratio (which defaults to true, but I add it here for completeness). the problem becomes clear.

// 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);

      

I have been working on this problem for several days and cannot find a solution. Any ideas? What am I missing?

+2


source to share


1 answer


The workaround I have used is the following:

I have created an event listener for the img displayable. Then, after loading the img, I manually set the height and width of the image. I know that I want the (preHeight) height to be hardcoded. Then I calculate the width and set it as the width of the image. For some reason, I had to use the explicitHeight and explicitWidth properties to finally get the correct sizing.



I hope this helps someone.

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; 
}

      

+1


source







All Articles