首页 > 解决方案 > 如何使用户上传的图片自动调整到我的 PHP 网站上的特定宽度和高度而不破坏尺寸?

问题描述

我创建了一个用户可以上传图片的网站,但我没有指定他们可以上传的图片尺寸。那么,如何让用户上传的图片自动调整到数据库中的特定宽度和高度,然后才能将其提取并显示在我的网站上?

标签: javascriptphphtmlcss

解决方案


早上好。

我想你可以使用这样的函数:

function resize_my_image_to_max_900($my_image){
    $control_width = imagesx($my_image);     // Store original width value
    $control_height = imagesy($my_image);     // Store original height value
    $n_width = $control_width;            // Default, case value <= 900
    $n_height = $control_height;           // Default, case value <= 900

    if($n_width >= 900 || $n_height >= 900):
        while(($n_width >= 900) || ($n_height >= 900)):
            $n_width = $control_width - ($control_width * 0.25);
            $n_height = $control_height - ($control_height * 0.25);
            
            if($n_width < 900 || $n_height < 900): break; endif;
        endwhile;
    endif;

    $new_image = imagecreatetruecolor($n_width, $n_height);

    imagealphablending($new_image, false);
    imagesavealpha($new_image, true);
    imagecopyresampled($new_image, $my_image, 0, 0, 0, 0, $n_width, $n_height, $control_width, $control_height);
}

祝您有美好的一天和出色的工作。


推荐阅读