0

我目前已经创建了这个脚本。

<?php
$allowedExts = array("png");
$extension = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000)
&& in_array($extension, $allowedExts))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Error: " . $_FILES["file"]["error"] . "<br>";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br>";
    echo "Type: " . $_FILES["file"]["type"] . "<br>";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
    echo "Stored in: " . $_FILES["file"]["tmp_name"];

    $path = "/path/to/file";
    move_uploaded_file($_FILES["file"]["tmp_name"], $path."/".$_SESSION['Username'].".png");

    }
  }
else
  {
  echo "Invalid file";
   }
?>

我希望为上传的图像指定最大高度和宽度。我该怎么做?

4

1 回答 1

0

你需要使用PHP函数getimagesize();

getimagesize() 函数不需要 GD 库。

尝试这个:

<?php
    // Set maximum width and height in pixels
    $maxwidth = 4000;
    $maxheight = 4000;

    $allowedExts = array("png");
    $extension = end(explode(".", $_FILES["file"]["name"]));
    if ((($_FILES["file"]["type"] == "image/gif")
    || ($_FILES["file"]["type"] == "image/jpeg")
    || ($_FILES["file"]["type"] == "image/png")
    || ($_FILES["file"]["type"] == "image/pjpeg"))
    && ($_FILES["file"]["size"] < 20000)
    && in_array($extension, $allowedExts))
      {
        // List the width, height, image type, img attributes of the uploaded file into the specified variables
        list($imgwidth, $imgheight, $imgtype, $imgattr) = getimagesize($_FILES["file"]["tmp_name"]);

        // If the image is too wide, or if the image is too tall, don't upload and tell the user.
        if($imgwidth < $maxwidth || $imgheight < $maxheight){
            if ($_FILES["file"]["error"] > 0)
            {
                echo "Error: " . $_FILES["file"]["error"] . "<br>";
            }
            else
            {
                echo "Upload: " . $_FILES["file"]["name"] . "<br>";
                echo "Type: " . $_FILES["file"]["type"] . "<br>";
                echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
                echo "Stored in: " . $_FILES["file"]["tmp_name"];

                $path = "/path/to/file";
                move_uploaded_file($_FILES["file"]["tmp_name"], $path."/".$_SESSION['Username'].".png");

            }
        }else{
            echo "File width or height is too large.";
        }
    }
    else
    {
        echo "Invalid file";
    }
?>
于 2013-02-09T03:25:04.337 回答