class.upload.php is a powerful and mature PHP class to manage uploaded files, and manipulate images in many ways. The script is available under a GPL license.
more info about the class
$handle->image_resize = true; $handle->image_ratio = true; $handle->image_x = 500; $handle->image_y = 500;
If I do this, it will stretch the smaller image out to have a width or height of 500:
I don't want any image to get stretched. If it's smaller than image_x or _y, I want it to stay smaller.