2

写真を選択するアップロードフォームがあります。アップロード時に、必要に応じて画像のサイズを変更します。

HEIGHT > WIDTH画像を伸ばす場所にアップロードした写真のようです。正常に動作する画像をアップロードするWIDTH > HEIGHTと。私はこれを理解しようとして頭を悩ませてきました。私はどの行が問題であるかを知っていると確信しており、コメントで指摘しました。

誰かが私の数学のどこが間違っているかを見ることができますか? ありがとう!

<?php
$maxWidth  = 900;
$maxHeight = 675;
$count     = 0;

foreach ($_FILES['photos']['name'] as $filename)
{
    $uniqueId   = uniqid();
    $target     = "../resources/images/projects/" . strtolower($uniqueId . "_" . $filename);
    $file       = $_FILES['photos']['tmp_name'][$count];    
    list($originalWidth, $originalHeight) = getimagesize($file);

    // if the image is larger than maxWidth or maxHeight
    if ($originalWidth > $maxWidth || $originalHeight > $maxHeight)
    {
        $ratio = $originalWidth / $originalHeight;

        // I think this is the problem line
        (($maxWidth / $maxHeight) > $ratio) ? $maxWidth = $maxWidth * $ratio : $maxHeight = $maxWidth / $ratio; 

        // resample and save
        $image_p    = imagecreatetruecolor($maxWidth, $maxHeight);
        $image      = imagecreatefromjpeg($file);
        imagecopyresampled($image_p, $image, 0, 0, 0, 0, $maxWidth, $maxHeight, $originalWidth, $originalHeight);
        $image      = imagejpeg($image_p, $target, 75);
    }
    else
    {
        // just save the image
        move_uploaded_file($file,$target);
    }
    $count += 1;
}
?>
4

1 に答える 1

3

スケーリングするときは、ターゲットの幅と高さの両方を変更する必要があります。

試す:

if ($originalWidth > $maxWidth || $originalHeight > $maxHeight)
{
    if ($originalWidth / $maxWidth > $originalHeight / $maxHeight) {
        // width is the limiting factor
        $width = $maxWidth;
        $height = floor($width * $originalHeight / $originalWidth);
    } else { // height is the limiting factor
        $height = $maxHeight;
        $width = floor($height * $originalWidth / $originalHeight);
    }
    $image_p    = imagecreatetruecolor($width, $height);
    $image      = imagecreatefromjpeg($file);
    imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $originalWidth, $originalHeight);
    $image      = imagejpeg($image_p, $target, 75);
}
于 2013-01-04T21:44:38.780 に答える