问题已编辑
下面是一个简单的脚本,允许用户上传图片。上传完成后,图片将显示为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'");
}
?>
我的一些代码的灵感来自这个问题: