Do you need the code, or just the functionality? I haven't tried this myself, but you may want to look at this:

"Create Bitmap from Selection"