所以我有一个图片上传脚本,问题是我想在上传之前调整图片大小。这是我现在的代码,
<?php
session_start();
$username = $_SESSION['user'];
include_once 'db.php';
define("UPLOAD_DIR", "uploads/");
$fileType = exif_imagetype($_FILES["myFile"]["tmp_name"]);
$allowed = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG);
if (!in_array($fileType, $allowed)) {
header('Location: edit.php');
exit();
}
if (!empty($_FILES["myFile"])) {
$myFile = $_FILES["myFile"];
if ($myFile["error"] !== UPLOAD_ERR_OK) {
echo "<p>An error occurred.</p>";
exit;
}
// ensure a safe filename
$name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);
//Start resize
$filename = $myFile;
$width = 200;
$height = 200;
header('Content-Type: image/jpeg');
list($width_orig, $height_orig) = getimagesize($filename);
$ratio_orig = $width_orig/$height_orig;
if ($width/$height > $ratio_orig) {
$width = $height*$ratio_orig;
} else {
$height = $width/$ratio_orig;
}
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
imagejpeg($image_p, null, 100);
// don't overwrite an existing file
$i = 0;
$parts = pathinfo($name);
while (file_exists(UPLOAD_DIR . $name)) {
$i++;
$name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
}
// preserve file from temporary directory
$success = move_uploaded_file($myFile["tmp_name"],
UPLOAD_DIR . $name);
if (!$success) {
echo "<p>Unable to save file.</p>";
exit;
}
// set proper permissions on the new file
chmod(UPLOAD_DIR . $name, 0644);
$upload_url = 'http://localhost/uploads/'.$name;
$stmt = $con->prepare("UPDATE users SET profile_picture=:picture WHERE username=:username;");
$stmt->bindValue(':picture', $upload_url, PDO::PARAM_STR);
$stmt->bindValue(':username', $username, PDO::PARAM_STR);
$stmt->execute();
}
?>
<a href="<?php echo $upload_url ?>">Click here</a>
这就是我得到的
警告:session_start():无法发送会话缓存限制器 - 已在/Users/matt/Desktop/Likers/upload.php中发送的标头(输出从/Users/matt/Desktop/Likers/upload.php:1开始)在第2行
警告:无法修改标头信息 - 第32行/Users/matt/Desktop/Likers/upload.php中已经发送的标头(在/Users/matt/Desktop/Likers/upload.php:1中开始输出)< / p>
警告:getimagesize()要求参数1为字符串,在第34行的/Users/matt/Desktop/Likers/upload.php中给出数组
警告:在第37行的/Users/matt/Desktop/Likers/upload.php中除以零
警告:imagecreatetruecolor():第45行/Users///Desktop/Likers/upload.php中的图像尺寸无效
警告:imagecreatefromjpeg()要求参数1为字符串,在第46行的/Users///Desktop/Likers/upload.php中给出数组
警告:imagecopyresampled()要求参数1为资源,第47行/Users///Desktop/Likers/upload.php中给出布尔值
警告:imagejpeg()要求参数1为资源,第49行/Users///Desktop/Likers/upload.php中给出布尔值
我不确定该怎么做。我这样做了吗?有一个更好的方法吗?任何帮助都会很棒。
答案 0 :(得分:1)
此错误解释了问题:
Warning: getimagesize() expects parameter 1 to be string, array given in /Users/matt/Desktop/Likers/upload.php on line 34
您只提供整个$_FILES["myFile"]
文件名。检查第27行:
$filename = $myFile;
应该是:
$filename = $myFile['tmp_name'];
希望有所帮助:)