Rather than using the temporary file, as described above, you can buffer the output stream. Someone else showed me this, and it seems to work very nicely.
//Start buffering the output stream
ob_start();
// output the image as a file to the output stream
Imagejpeg($im);
//Read the output buffer
$buffer = ob_get_contents();
//clear the buffer
ob_end_clean();
//use $buffer as you wish...