PHP从url增加图像分辨率然后裁剪

问题描述:

I have images with resolution of 720x1280 and I would need to store them on server with resolution 800x1500. Since 720x1280 increased to height 1500 gives resolution of 844x1500 I would also need to crop image, remove 22 pixels from the left and right side.

For now I have this:

$img_url = file_get_contents($url);

$img = imagecreatefromstring($img_url);

$width = imagesx($img);
$height = imagesy($img);

$new_width = '800';
$new_height = '1500';

$thumb = imagecreatetruecolor($new_width, $new_height);

imagecopyresampled($thumb, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

imagejpeg($thumb, $name, 100);

imagedestroy($thumb);
imagedestroy($img);

But the problem is that image is not cropped, 22 pixels from the left and right side are not removed.

Is there a way to do this, to first increase image resolution from url and then crop?

我有分辨率为720x1280的图像,我需要将它们存储在分辨率为800x1500的服务器上。 因为720x1280增加了 高度1500给出844x1500的分辨率我还需要裁剪图像,从左侧和右侧删除22个像素。 p>

现在我有这个: p>

  $ img_url = file_get_contents($ url); 
 
 $ img = imagecreatefromstring($ img_url); 
 
 $ width = imagesx($ img); 
 $ height = imagesy($ img)  ); 
 
 $ new_width ='800'; 
 $ new_height ='1500'; 
 
 $ thumb = imagecreatetruecolor($ new_width,$ new_height); 
 
imagecopyresampled($ thumb,$ img,0  ,0,0,0,$ new_width,$ new_height,$ width,$ height); 
 
imagejpeg($ thumb,$ name,100); 
 
imagedestroy($ thumb); 
imagedestroy($ img);  
  code>  pre> 
 
 

但问题是没有裁剪图像,左边和右边22像素都没有被删除。 p>

有没有办法做到这一点,首先从网址提高图像分辨率然后裁剪? p> div>

Googling php image crop reveals the secret:

$rect = [22, 0, 800, 1500]
$thumb = imagecrop($thumb, $rect)

In this line:

imagecopyresampled($thumb, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

you just scale your original image to new dimensions. As the documentation says:

If the source and destination coordinates and width and heights differ, appropriate stretching or shrinking of the image fragment will be performed.

You need to set:

$shiftX = 22*(1280/1500); // consider passing variables rather than constant values
$scaledWidth = 720-$shiftX*2;
imagecopyresampled($thumb, $img, 0, 0, $shiftX, 0, $new_width, $new_height, $scaledWidth, $height);

which cuts out the required (proportional) rectangle of the source image to paste it in you destination picture.