简体   繁体   中英

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM