我在我的网站上使用 PHP, jQuery, AJAX, HTML, 等 . 我是PHP的新手 .
我在WebApp中使用了一个jQuery图像滑块 . 对于此图像滑块用户上载图像 . 此外,这些上载的图像显示在该图像滑块中 . 这个功能对我来说很好 .
此图像滑块的固定宽度和高度为 940 px * 370 px . 我想允许用户上传尺寸应大于或等于 940 px * 370 px 的图像 .
假设用户上传尺寸为 2215 px * 875 px 的图像,则在将图像上传到服务器之前(即在将图像保存到服务器之前),应将此图像重新调整为尺寸 940 px * 370 px . 只有在将上传的图像重新调整为 940 px 370 px* 之后,它才会保存到服务器 .
在重新调整大小的过程中,图像质量不得受到影响 . 重新调整大小的图像应该看起来像用户上传的原始图像 . 它不应该在任何意义上收缩或拉伸 .
如何使用PHP GD和图像函数以最佳方式实现此功能?
为了您的参考,我把它放在我试过的文件上传功能的代码之下:
HTML Code :
<html>
<body>
<form action="upload_file.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
PHP Code :
<?php
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
$image_dimesnions = getimagesize($_FILES['file']['tmp_name']);
$image_width = $image_dimesnions[0];
$image_height = $image_dimesnions[1];
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] > 5242880)
&& ($image_width < 940 || $image_height < 370)
&& in_array($extension, $allowedExts)) {
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_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 "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " already exists. ";
} else {
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
}
} else {
echo "Invalid file";
}
?>
1 回答
您可以使用imagemagick命令行工具或使用PHP GD Library在服务器上执行此操作 .
更多信息链接ImageMagick -
About ImageMagick
Command Line Options
Resize
PHP GD Library的信息链接 -
PHP GD
imagecreatefromjpeg
imagecreatefrompng
imagecreatefromgif
使用下面的命令转换图像 -
使用以下代码PHP GD-
Note: 您必须自己决定哪种方法可以调整图像大小 .