繁体   English   中英

使用PHP上传图像之前检查图像尺寸(高度和宽度)

[英]Check image dimensions (height and width) before uploading image using PHP

如何使用PHP在上传图像之前检查高度和宽度。

我必须先上传图片并使用“getimagesize()”吗? 或者我可以在使用PHP上传之前检查一下吗?

<?php

foreach ($_FILES["files"]["error"] as $key => $error) {
if(
$error == UPLOAD_ERR_OK
&& $_FILES["files"]["size"][$key] < 500000 
&& $_FILES["files"]["type"][$key] == "image/gif"
|| $_FILES["files"]["type"][$key] == "image/png"
|| $_FILES["files"]["type"][$key] == "image/jpeg"
|| $_FILES["files"]["type"][$key] == "image/pjpeg" 
){


$filename = $_FILES["files"]["name"][$key];








if(HOW TO CHECK WIDTH AND HEIGHT)
{
echo '<p>image dimenssions must be less than 1000px width and 1000px height';
}


}







?>

我们可以轻松地使用临时文件。

$image_info = getimagesize($_FILES["file_field_name"]["tmp_name"]);
$image_width = $image_info[0];
$image_height = $image_info[1];

这就是我解决它的方式。

$test = getimagesize('../bilder/' . $filnamn);
$width = $test[0];
$height = $test[1];

if ($width > 1000 || $height > 1000)
{
echo '<p>iamge is to big';
unlink('../bilder/'.$filnamn);
}

如果文件位于$_FILES数组中(因为它是以Multipart形式选择的),它已经上传到服务器(通常是/ tmp或类似的文件路径),所以你可以继续使用getimagesize() php中的函数来获取维度(包括所有细节作为数组)。

这对我有用

$file = $_FILES["files"]['tmp_name'];
list($width, $height) = getimagesize($file);

if($width > "180" || $height > "70") {
    echo "Error : image size must be 180 x 70 pixels.";
    exit;
}

在实际上传发生之前,您需要在客户端上执行某些操作。
随着(服务器端),PHP,您可以检查该文件已被上传后,才尺寸或上传挂钩 可能在图像上载(从图像文件头数据)。

所以你的选择是flash,也许是带有FileAPI的html5(没有测试过,也许那是不可行的),java-applet,silverlight,...

要获取图像的宽度和高度,请使用getimagesize(path_name) ,此函数返回包含height,width,image_type常量和其他图像相关信息的数组。 通过以下代码,您可以实现这一点。

注意 - 需要传递图像的临时位置,并在使用move_upload_file()之前使用以下代码,否则它会将文件移动到目标路径,您将无法获得图像的所需结果

$imageInformation = getimagesize($_FILES['celebrity_pic']['tmp_name']);
print_r($imageInformation);

$imageWidth = $imageInformation[0]; //Contains the Width of the Image

$imageHeight = $imageInformation[1]; //Contains the Height of the Image

if($imageWidth >= your_value && $imageHeight >= your_value)
{
  //Your Code
}

非常重要 - 如果您使用Dreamweaver进行编码,并且尝试使用$_FILES[anyFormName][tmp_name]来获取图像大小,它将在实时视图中显示错误。我花了一些时间来解决这个问题。

 array getimagesize ( string $filename [, array &$imageinfo ] )

getimagesize()函数将确定任何给定图像文件的大小,并返回尺寸以及文件类型和要在普通HTML IMG标记内使用的高度/宽度文本字符串以及相应的HTTP内容类型。

欲了解更多信息,请访问网站: http//www.php.net/manual/en/function.getimagesize.php

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM