php изменить размер изображения после загрузки и обрезать его по центру - PullRequest
1 голос
/ 06 сентября 2011

У меня есть профиль пользователя в php, и я хочу дать пользователям возможность изменить изображение своего профиля.Но когда они отправляют свою новую фотографию через $ _POST, я хочу, чтобы ее размер был изменен до:

высота: 110px |ширина: соответствует высоте (если ширина больше высоты)

ширина: 110px |высота: соответствует ширине (если высота больше ширины)

, когда изменение размера выполнено, я хочу обрезать изображение, чтобы оно стало 110px x 110px, но я хочу, чтобы оно было отцентрировано.

Например, если пользователь загружает изображение шириной 110px и высотой 200px (размеры после изменения размера), новое изображение после кадрирования будет обрезано на 110x110 на 90px справа.То, что я хочу, это обрезать 45 пикселей слева и еще 45 пикселей справа, чтобы она была отцентрирована

, функция будет принимать .png, .gif и .jpg изображений и сохранит новое изображение только в формате jpgформат независимо от того, какой был исходный формат.

Я много искал, чтобы создать такую ​​функцию, и я нашел ответ, но каждый раз, когда я пытался изменить какую-то мелкую деталь, все перестало работать должным образом.

Мой код пока:

<?php

$userfile_name = $_FILES["sgnIMG"]["name"];
$userfile_tmp = $_FILES["sgnIMG"]["tmp_name"];
$userfile_size = $_FILES["sgnIMG"]["size"];
$filename = basename($_FILES["sgnIMG"]["name"]);
$file_ext = substr($filename, strrpos($filename, ".") + 1);
$large_image_location = $target_path . $filename;
$ext = '';

if ($file_ext == 'jpg') {
    $ext = 1;
} else if ($file_ext == 'gif') {
    $ext = 2;
} else if ($file_ext == 'png') {
    $ext = 3;
} else {
    $ext = 0;
}

$target = $target_path . basename($_FILES["sgnIMG"]["name"]);

if (move_uploaded_file($userfile_tmp, $target)) {
    $newImg = resize110($target, $ext);
    if (isset($_POST['imupd']) && ($_POST['imupd'] == 'up')) {
        $sql = "UPDATE users SET avatar='" . str_replace('im/users/', '', $newImg) . "' WHERE id=" . $_SESSION['sesID'] . "";
        $result = mysql_query($sql);
        if ($result) {
            echo '<img src="' . $newImg . '" width="110" title="' . $file_ext . '"/>';
        } else {
            echo '<img src="im/avatars/px.png" width="110" title="' . $file_ext . '"/>';
        }
    }
} else {

}

function getHeight($image)
{
    $sizes = getimagesize($image);
    $height = $sizes[1];
    return $height;
}

function getWidth($image)
{
    $sizes = getimagesize($image);
    $width = $sizes[0];
    return $width;
}

function resize110($image, $ext)
{
    chmod($image, 0777);
    $oldHeight = getHeight($image);
    $oldWidth = getWidth($image);
    if ($oldHeight < $oldWidth) {
        $newImageHeight = 110;
        $newImageWidth = ceil((110 * $oldWidth) / $oldHeight);
        imagecopyresampled($newImage, $source, -ceil(($newImageWidth - 110) / 2), 0, 0, 0, $newImageWidth, $newImageHeight, $oldWidth, $oldHeight);
    } else {
        $newImageHeight = ceil((110 * $oldHeight) / $oldWidth);
        $newImageWidth = 110;
        imagecopyresampled($newImage, $source, 0, -ceil(($newImageHeight - 110) / 2), 0, 0, $newImageWidth, $newImageHeight, $oldWidth, $oldHeight);
    }
    $newImage = imagecreatetruecolor(110, 110);
    chmod($image, 0777);
    return $image;
    switch ($ext) {
        case 1;
            $source = imagecreatefromjpeg($image);
            break;
        case 2;
            $source = imagecreatefromgif($image);
            break;
        case 3;
            $source = imagecreatefrompng($image);
            break;
    }

    imagejpeg($newImage, $image, 90);
    return $image;
}

1 Ответ

1 голос
/ 18 сентября 2011

Я много осматривался и комбинировал разные части кода, которые нашел. Таким образом, этот скрипт возьмет изображение jpg, gif png, измените его размер до 110px ширины, если ширина больше 110px высоты, если высота больше. Соотношение сторон будет сохраняться, поэтому оставшиеся пиксели, разделенные на 2, будут использоваться для центрирования изображения.

для другого размера просто измените 110 везде.

=============================================== ===================================

<?php

// pfpic  ->  the name of the <input type="file" name="pfpic"/> where user chooses file

$target_path = "im/users/";                                // the directory to store the uploaded and then resampled image
$userfile_name = $_FILES["pfpic"]["name"];                  // the name that the image file will have once uploaded
$userfile_tmp = $_FILES["pfpic"]["tmp_name"];                   // the temporary name the server uses to store the file
$userfile_size = $_FILES["pfpic"]["size"];                  // the size of the file that we want to upload
$filename = basename($_FILES["pfpic"]["name"]);             // the full name of the file
$file_ext = substr($filename, strrpos($filename, ".") + 1);  // the file extension
$large_image_location = $target_path.$filename;                  // the full path to the file
$ext='';


if($file_ext=='jpg')
{
    $ext=1;
}
else if ($file_ext=='gif')
{
    $ext=2;
}
else if ($file_ext=='png')
{
    $ext=3;
}
else
{
    $ext=0;
}

    $target = $target_path.basename(sha1($_SESSION['sesID']).'.'.'jpg');
    if($ext!=0)
    {
        if(move_uploaded_file($userfile_tmp,$target))
        {
            $newImg=resize110($target,$ext);
            echo '<img src="'.$newImg.'"/>';
        }
        else
        {
            echo 'the file could not be uploaded, please try again';
        }
    }
    else
    {
        echo 'this file extension is not accepted, please use "jpg", "gif" or "png" file formats';
    }

    function getHeight($image) 
    {
        $sizes = getimagesize($image);
        $height = $sizes[1];
        return $height;
    }

    function getWidth($image) 
    {
        $sizes = getimagesize($image);
        $width = $sizes[0];
        return $width;
    }


    function resize110($image,$ext) 
    {
        chmod($image, 0777);
        $oldHeight=getHeight($image);
        $oldWidth=getWidth($image);
        switch ($ext)
        {
            case 1;
                $source = imagecreatefromjpeg($image);
            break;

            case 2;
                $source = imagecreatefromgif($image);
            break;

            case 3;
                $source = imagecreatefrompng($image);
            break;
        }
        $newImage = imagecreatetruecolor(110,110);
        $bgcolor = imagecolorallocate($newImage, 255, 255, 255);
        imagefill($newImage, 0, 0, $bgcolor);       // use this if you want to have a white background instead of black


        // we check tha width and height and then we crop the image to the center
        if($oldHeight<$oldWidth)
        {
            $newImageHeight = 110;
            $newImageWidth = ceil((110*$oldWidth)/$oldHeight);
            imagecopyresampled($newImage,$source,-ceil(($newImageWidth-110)/2),0,0,0,$newImageWidth,$newImageHeight,$oldWidth,$oldHeight);
        }
        else
        {
            $newImageHeight = ceil((110*$oldHeight)/$oldWidth);
            $newImageWidth = 110; 
            imagecopyresampled($newImage,$source,0,-ceil(($newImageHeight-110)/2),0,0,$newImageWidth,$newImageHeight,$oldWidth,$oldHeight);
        }

        //we save the image as jpg resized to 110x110 px and cropped to the center. the old image will be replaced
        imagejpeg($newImage,$image,90);

        return $image;

    }

?>

...