Code I/O

A topnotch WordPress.com site

5 Minutes on Adobe Flex – Resize image to fixed height and width …

1 Comment

Off late writing some code for my project, had to write a piece to resize and fit images to fixed constraints.  The exercise was simple and yielded good results.  Idea was to get images, make them uniform so that it can be used to produce elegant UI experience.

Need: scale up/down images, keep aspect ratio (but of course, if the image is too small to fit, then there will be distortion; presume that it is acceptable).

The constraints are predefined somewhere, say the user wants all the images to be of some fixed width and height.

Algorithim:

Search for images (from yahoo or google) using API

Cache images

Resize and Save them

Let me now talk about resize for instance, the function resizeBitmap will transform the original image so be cautious if you want to modify a clone.

public function resizeBitmap(bitmap:Bitmap, maxWidth:Number, maxHeight:Number):void
{
	var bitmapData:BitmapData = bitmap.bitmapData;
	var scaleFactor:Number = 1;
	
	var newWidth:Number = maxWidth;
	var newHeight:Number = maxHeight;
	
	if(bitmapData.width > bitmapData.height) 
	{
		scaleFactor = maxWidth / bitmapData.width;
	}
	else 
	{
		scaleFactor = maxHeight / bitmapData.height;
	}

	newWidth = bitmapData.width * scaleFactor;
	newHeight = bitmapData.height * scaleFactor;
	
	var scaledBitmapData:BitmapData = new BitmapData(newWidth, newHeight);
	var scaleMatrix:Matrix = new Matrix();
	scaleMatrix.scale(scaleFactor, scaleFactor);
	
	scaledBitmapData.draw(bitmap, scaleMatrix);
	bitmap.bitmapData = scaledBitmapData;
}
Advertisements

One thought on “5 Minutes on Adobe Flex – Resize image to fixed height and width …

  1. Thanks a lot, for this post. It helped me a lot …

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s