Crop bitmapdata under mask to create new bitmap AS3

So you want to be able to crop an image based on what is viewable through the mask and then saved that cropped image out to a new file. For two days I played about with code to trying to get this to work. The main problem for me was that the image would be dragged about underneath the mask. This was proving a bit confusing for me in getting the coordinates to crop from. Well thankfully I was able to get it to work the way I wanted. So now that I have it working I thought I would share the code as whilst doing research for a solution I didn’t find anything of real use.

Yes you can use any shape mask you want. But you must remember that your only taking the size of the mask and using that against the visible area of the mask to tell the script where and what to crop. The cropped image does not come out as the shape of the mask. It’s only crops the image so it fits snugly into the mask area.