Php 上传时缩放后如何保存新的图像尺寸?
问题已编辑 下面是一个简单的脚本,允许用户上传图片。上传完成后,图片将显示为170px(高)x 150px(宽)的缩略图 大多数图片在调整大小后看起来都扭曲了,所以我想我也需要对它们进行缩放 我一直在保存新的图像尺寸参见待办事项。Php 上传时缩放后如何保存新的图像尺寸?,php,file-upload,upload,image-resizing,Php,File Upload,Upload,Image Resizing,问题已编辑 下面是一个简单的脚本,允许用户上传图片。上传完成后,图片将显示为170px(高)x 150px(宽)的缩略图 大多数图片在调整大小后看起来都扭曲了,所以我想我也需要对它们进行缩放 我一直在保存新的图像尺寸参见待办事项。 <?php if ($_SERVER["REQUEST_METHOD"] == "POST") { $maxWidth = 150; $maxHeight = 170; $name = $_FILES ['image'] ['
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$maxWidth = 150;
$maxHeight = 170;
$name = $_FILES ['image'] ['name'];
$type = $_FILES ["image"] ["type"];
$size = $_FILES ["image"] ["size"];
$tmp_name = $_FILES ['image'] ['tmp_name'];
list($originalWidth, $originalHeight) = getimagesize($tmp_name);
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);
}
// Resample
$image_p = imagecreatetruecolor($maxwidth, $maxheight);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $maxwidth, $maxheight,
$originalWidth, $originalHeight);
TODO: how do I save the new dimensions to $location ?
//start upload process
$RandomNumber = uniqid();
$location = "uploads/$RandomNumber";
move_uploaded_file($tmp_name, $location);
query("UPDATE users SET profilepic = '".$location."' WHERE id = '$id'");
}
?>
至于您的问题:“如何获得用户想要上传的图片的初始尺寸?”
从手册中:
列表($width、$height、$type、$attr)=getimagesize(“img/flag.jpg”)强>
考虑到这一点,您可以将上面示例中的文件路径替换为$_FILES[“image”]以获取维度数据
获得原始尺寸后,可以将图像调整为更小,同时保留原始纵横比
对于错误检查,您可能希望检查$_FILES[“image”]中是否只有一个文件,或者在允许使用每个图像的HTML输入标记的相同名称进行多个图像上载的情况下,循环一个数组。我有一个自定义类可以帮助我在项目中执行此操作。请随意使用我的代码:
+1。我刚刚编辑了我的问题,以便我的问题更容易理解,请看一下待办事项。也许你能帮上忙。当你说“如何将新尺寸保存到$location?”时,你是在问如何将新的、调整大小的图像保存到$location?如果是这样,我相信您应该像这样使用PHP函数imagejpeg:imagejpeg($image\u p,$location)
。有关更多示例,请参见。