问题已编辑
下面是一个允许用户上传图片的简单脚本。上传完成后,图片将显示为 170px(h) x 150px(w) 缩略图。
大多数图片在调整大小后看起来都会失真,所以我想我也需要缩放它们。
我坚持保存新的图像尺寸。请参阅待办事项。
<?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'");
}
?>
我的一些代码的灵感来自这个问题:
使用 PHP 调整扭曲的图像大小
至于你的问题:"我怎样才能获得用户想要上传的图片的初始尺寸?
从手册:
list($width, $height, $type, $attr) = getimagesize("img/flag.jpg");
考虑到这一点,您可以将上述示例中的文件路径替换为 $_FILES["image"] 以获取维度数据。
获得原始尺寸后,您可以在保留原始纵横比的同时将图像调整为更小。
对于错误检查,您可能希望检查 $_FILES["image"] 中是否只有一个文件,或者在允许对每个图像的 HTML 输入标记使用相同的名称上传多个图像的情况下遍历数组。
我有一个自定义类可以帮助我在项目中执行此操作。随意使用我的代码:https://gist.github.com/695Multimedia/7117003