如何使PHP不会裁剪到我调整大小的左上角


How to make PHP not crop to the top left of my resizing?

我正在用PHP将图像(用于用户的配置文件图标)调整为200x200大小,这样我就不会在页面上塞满巨大的图像。然而,如果不是正方形,我的代码似乎会裁剪以删除图像左上角以外的任何内容。如何将其正常调整为200x200?这是我的代码:

    <?php
//Function that will create a thumbnail of images submitted
function createThumbnail($image_name, $thumbnail_name, $size, $type) {
                //creates the image based on the type of file
                if($type == "image/jpeg") {
                    $image = imagecreatefromjpeg($image_name); 
                }
                else if ($type == "image/png") {
                    $image = imagecreatefrompng($image_name);
                }
                else if ($type == "image/gif") {
                    $image = imagecreatefromgif($image_name);
                }

                $thumbnail = imagecreatetruecolor($size, $size); 

                // if height and width are not equal... 
                if(imagesx($image) > imagesy($image)){
                    imagecopyresized($thumbnail, $image, 0, 0, 0, 0, 200, 200, imagesy($image), imagesy($image)); 
                }
                else {
                    imagecopyresized($thumbnail, $image, 0, 0, 0, 0, 200, 200, imagesx($image), imagesx($image)); 
                }

                if($type == "image/jpeg") {
                    imagejpeg($thumbnail, $thumbnail_name, 100);  
                }
                else if ($type == "image/png") {
                    imagepng($thumbnail, $thumbnail_name, 0); 
                }
                else if ($type == "image/gif") {
                    imagegif($thumbnail, $thumbnail_name); 
                }
}
    ?>

谢谢大家!-Adam

获取图像大小数据

$imageData = @getimagesize($image);

计算比率

  1. 如果图像宽度和高度都小于200,我们可以继续使用相同的大小
  2. 如果宽度和高度大于200,我们需要计算新的宽度高度乘以比值200/max(宽度、高度)避免裁剪顶部(如果宽度更大)或左侧(如果高度为更多)

$ratio = min(200/$imageData[0],200/$imageData[1],1);

计算新的宽度和高度

$width = (INT) round($ratio * $imageData[0]);
$height = (INT) round($ratio * $imageData[1]);

因此,调整大小的代码变成如下

imagecopyresampled($thumbnail, $image, 0, 0, 0, 0, $width, $height,$imageData[0], $imageData[1])

如果比率为1,则没有问题,但如果比率小于1,则我们获得的宽度/高度图像小于所需的图像,即200*200。

为此,您可以创建一个新的透明png或白色(200*200)jpg,并适当地放置新生成的图像,即如果高度较小,则将其垂直居中,或者如果宽度较小,则使其水平居中并保存该文件。

这可以使用此链接中发布的类似方法来完成:http://php.net/manual/en/image.examples-watermark.php

来源:http://xlab.co.in/resize-an-image-without-crop-using-php/