Thursday, March 25, 2010

ActionScript 3 - Crop and Resize Image

I needed to allow a user to select an image on their computer, crop that image down to whatever area they preferred, then save the image to the server. However, we wanted to limit the size of the image to 300 by 300. So if they uploaded an image of 1000 by 1000, the selected area needed to be reduced to a max of 300 by 300.

Okay, so the front end is Flash/Flex3, and the server end it C#.

The Flex part:
First to crop an image, I used the free tool called ImageCropper from FlexBlocks. This snazzy little tool made it very easy to crop the image, and then view the cropped image in an image component.

The drawback was that it did not seem to resize the underlying BitmapData like I needed. At least, I could not tell from any of the documentation that it would do this for me.

So I found this code on the 'net that did the most accurate job of resizing the image.

//this is the imagecropper working in this function
private function doCrop():void {

  // Get the cropped BitmapData
  var loadBD:BitmapData;
  loadBD = imageCropper.croppedBitmapData;

  var croppedBitmap:Bitmap;
  croppedBitmap = ResizeImage.resizeIt(loadBD, 300, 300) as Bitmap;

  //set preview image component's source to cropped bitmap
  croppedImage.source = croppedBitmap;

}


And here is the re-size function that someone wrote, I might have changed a few lines. Thanks to whoever wrote and shared this code...

public static function resizeIt(target:BitmapData, width:Number, height:Number):Bitmap{

  var ratio:Number = target.width/target.height;
  var targetHeight:Number = height;//now instead of setting the picture

  //size we calculate what the size should be with two new variables.
  var targetWidth:Number = targetHeight*ratio;
    if(targetWidth>width){
      targetWidth = width;
      targetHeight = targetWidth/ratio;
    }

  var bmp:BitmapData = new BitmapData(targetWidth, targetHeight);

  //create a bitmapData and pass it the size that the picture should be

  //create a matrix that we'll use to scale the picture
  var matrix:Matrix = new Matrix();

  //set the scale for the matrix
  matrix.scale((targetWidth/target.width), (targetHeight/target.height));

  //draw our bitmapData using our matrix, smooth the picture using true
  bmp.draw(target,matrix,null,null,null,true);


  var bitmap:Bitmap = new Bitmap(bmp);

  //create a bitmap and pass it our resized bitmapData
  bitmap.x = width/2-bitmap.width/2;//set the bitmap position
  bitmap.y = height/2-bitmap.height/2;//set the bitmap position

 return bitmap;//return the bitmap
}

When I get some time, I will post how I did the second part of this task which was sending the bitmap data over to .NET (C#), reading into a file and saving it to the server! So in the end, it is possible to do all this, even if I don't understand every last bit of it :)



Hope that helps.

No comments:

Post a Comment