自动裁剪图像并将其调整为特定尺寸

时间:2014-12-20 16:46:07

标签: php image

我正在为我的网站制作照片库。这是一个微缩模型(400 x 300px)。当用户单击微缩图时,图像将以其完整大小显示。用户可以上传图片但我的问题是如何裁剪和/或调整上传的图片大小以创建尺寸为400 x 300px 的缩小比例,保持比例

1 个答案:

答案 0 :(得分:4)

我在我的一些项目中完成了这项工作,这对你来说不适合所有的东西。这将有助于您获得更好的解决方案。

// RESIZE AN IMAGE PROPORTIONALLY AND CROP TO THE CENTER


function resize_and_crop($original_image_url, $thumb_image_url, $thumb_w, $thumb_h, $quality=75)
{
    // ACQUIRE THE ORIGINAL IMAGE: http://php.net/manual/en/function.imagecreatefromjpeg.php
    $original = imagecreatefromjpeg($original_image_url);
    if (!$original) return FALSE;

    // GET ORIGINAL IMAGE DIMENSIONS
    list($original_w, $original_h) = getimagesize($original_image_url);

    // RESIZE IMAGE AND PRESERVE PROPORTIONS
    $thumb_w_resize = $thumb_w;
    $thumb_h_resize = $thumb_h;
    if ($original_w > $original_h)
    {
        $thumb_h_ratio  = $thumb_h / $original_h;
        $thumb_w_resize = (int)round($original_w * $thumb_h_ratio);
    }
    else
    {
        $thumb_w_ratio  = $thumb_w / $original_w;
        $thumb_h_resize = (int)round($original_h * $thumb_w_ratio);
    }
    if ($thumb_w_resize < $thumb_w)
    {
        $thumb_h_ratio  = $thumb_w / $thumb_w_resize;
        $thumb_h_resize = (int)round($thumb_h * $thumb_h_ratio);
        $thumb_w_resize = $thumb_w;
    }

    // CREATE THE PROPORTIONAL IMAGE RESOURCE
    $thumb = imagecreatetruecolor($thumb_w_resize, $thumb_h_resize);
    if (!imagecopyresampled($thumb, $original, 0,0,0,0, $thumb_w_resize, $thumb_h_resize, $original_w, $original_h)) return FALSE;

    // ACTIVATE THIS TO STORE THE INTERMEDIATE IMAGE
    // imagejpeg($thumb, 'RAY_temp_' . $thumb_w_resize . 'x' . $thumb_h_resize . '.jpg', 100);

    // CREATE THE CENTERED CROPPED IMAGE TO THE SPECIFIED DIMENSIONS
    $final = imagecreatetruecolor($thumb_w, $thumb_h);

    $thumb_w_offset = 0;
    $thumb_h_offset = 0;
    if ($thumb_w < $thumb_w_resize)
    {
        $thumb_w_offset = (int)round(($thumb_w_resize - $thumb_w) / 2);
    }
    else
    {
        $thumb_h_offset = (int)round(($thumb_h_resize - $thumb_h) / 2);
    }

    if (!imagecopy($final, $thumb, 0,0, $thumb_w_offset, $thumb_h_offset, $thumb_w_resize, $thumb_h_resize)) return FALSE;

    // STORE THE FINAL IMAGE - WILL OVERWRITE $thumb_image_url
    if (!imagejpeg($final, $thumb_image_url, $quality)) return FALSE;
    return TRUE;
}


// USE CASE
echo '<a target="_blank" href="orig_600x374.jpg">Original 600x374</a><br/>';

resize_and_crop('orig_600x374.jpg', 'temp_100x100.jpg', 100, 100);
echo '<a target="_blank" href="temp_100x100.jpg">100x100</a><br/>';

resize_and_crop('orig_600x374.jpg', 'temp_200x100.jpg', 200, 100);
echo '<a target="_blank" href="temp_200x100.jpg">200x100</a><br/>';

resize_and_crop('orig_600x374.jpg', 'temp_200x300.jpg', 200, 300);
echo '<a target="_blank" href="temp_200x300.jpg">200x300</a><br/>';