Q:

GD resize image and crop edges

Basically if I have a 3400x3400 image and my target size is 340x200 then I would like to grab the respective 3400x2000 from the middle of the original image and then scale it down to 340x200, I have a rough idea of how it will look, here is what I have so far:
$RealWidth=164;
$RealHeight=126;
$org_img = imagecreatefromjpeg($newname);    
list($width, $height) = getimagesize($newname);
$ratio2 = $height/$width;
$ratio = $RealHeight/$RealWidth;
$img = imagecreatetruecolor($RealWidth,$RealHeight);
$ims = getimagesize($newname);
imagecopyresized($img,$org_img, 0, 0, 0, 0, $RealWidth, $RealHeight, $height*$ratio2, $height);
imagejpeg($img,$newname,90);
imagedestroy($img);

I am a bit confused with the math, I also want it to be able to crop a region from the top/bottom if needed as well. 

A:

Your code with the 'new' math inserted into it:
$RealWidth=164;
$RealHeight=126;
$org_img = imagecreatefromjpeg($newname);
list($width, $height) = getimagesize($newname);
$ratio = $width / $height < $RealWidth / $RealHeight ?  $RealWidth / $width : $RealHeight / $height;
$src_x = round($width  / 2 - ($RealWidth  / 2) / $ratio);
$src_y = round($height / 2 - ($RealHeight / 2) / $ratio);
$src_w = round($RealWidth  / $ratio);
$src_h = round($RealHeight / $ratio);
$img = imagecreatetruecolor($RealWidth,$RealHeight);
$ims = getimagesize($newname);
imagecopyresized($img, $org_img, 0, 0, $src_x, $src_y, $RealWidth, $RealHeight, $src_w, $src_h);
imagejpeg($img,$newname,90);
imagedestroy($img);

