【发布时间】:2015-02-22 04:48:18
【问题描述】:
我一直在尝试从 HTML 表单中获取文件,然后创建一个新文件并使用“imagecopyresampled”从中获取中心方块,适合 X 或 Y,具体取决于哪个更小。
不幸的是,我对处理这么多图像和临时名称感到有些困惑,并且在将文件复制到系统上的用户文件时遇到了麻烦。 代码如下:
if($_FILES){
$valid = validate_image("avatar");
if ($valid){
list($width, $height, $type) = getimagesize($_FILES['avatar']['tmp_name']);
$scale = $width/$height;
$pixels = 150;
$tmp_name = $_FILES['avatar']['tmp_name'];
switch ($type) {
case IMAGETYPE_GIF:
$source = imagecreatefromgif($tmp_name);
break;
case IMAGETYPE_JPEG:
case IMAGETYPE_JPG:
$source = imagecreatefromjpeg($tmp_name);
break;
case IMAGETYPE_PNG:
$source = imagecreatefrompng($tmp_name);
break;
}
$upload = imagecreatetruecolor($pixels, $pixels);
//sketchy image math: Get whichever coordinate is smaller and that will be 150 on the thumbnail from top to bottom (or left to right).
//Then for the other one you know the size will be 150, but only for the part starting at (Coordinate/2)-SMALLERCOORD/2 to (coord/2)+SMALLERCOORD/2
if ($width>$height){
imagecopyresampled ($upload, $source, 0, 0, 0, ($width-$height/2), 150, 150, $height, $height);
} else if ($width<=$height){
imagecopyresampled ($upload, $source, 0, 0, 0, ($height-$width/2), 150, 150, $width, $width);
}
$name = "./users/$id/avatar.png";
imagepng($upload, $tmp_name);
if (!(move_uploaded_file($tmp_name, $name))) $fail .= "<h3>ERROR UPLOADING AVATAR. TRY AGAIN LATER OR CONTACT US.</h3><br>";
}
}
首先让我看看我是否理解代码是如何正常工作的: 我得到文件,检查它是否对我的功能有效。然后我得到它的大小和类型。我检查类型并从中在服务器内存上创建一个图像,并在我想要的大小上创建另一个空图像。然后我实际上将调整大小和裁剪的图像复制到我创建的上传图像上。 如果我愿意,我可以使用 imagedestroy 删除临时“源”图像,对吗? 接下来,我尝试从服务器内存中的“上传”图像制作一个 png 文件。 这是我认为我弄错的地方,我无法覆盖临时文件,可以吗? 然后我尝试将图像临时图像放在应该上传的位置,但这不起作用。
我做对了吗?如何修复此代码? 感谢您的关注。
【问题讨论】:
标签: php image upload resize php-gd