【发布时间】:2014-08-26 18:48:51
【问题描述】:
所以我有一个图片上传脚本,问题是我想在上传之前调整图片大小。这是我现在的代码,
<?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 发送的标头
警告:getimagesize() 期望参数 1 是字符串,数组在 /Users/matt/Desktop/Likers/upload.php 第 34 行给出
警告:第 37 行 /Users/matt/Desktop/Likers/upload.php 中除以零
警告:imagecreatetruecolor():第 45 行 /Users///Desktop/Likers/upload.php 中的图像尺寸无效
警告:imagecreatefromjpeg() 期望参数 1 为字符串,数组在 /Users///Desktop/Likers/upload.php 第 46 行给出
警告:imagecopyresampled() 期望参数 1 是资源,布尔值在第 47 行的 /Users///Desktop/Likers/upload.php 中给出
警告:imagejpeg() 期望参数 1 是资源,布尔值在第 49 行的 /Users///Desktop/Likers/upload.php 中给出
我不确定该怎么做。我这样做正确吗?有一个更好的方法吗?任何帮助都会很棒。
【问题讨论】:
-
您可能正在使用
UTF-8(with BOM)。请改用UTF-8(without BOM)。 -
这有什么帮助?我担心实际调整大小。我知道如何修复标题错误@IanMustafa
-
我会在哪里使用它? @CertaiN
-
@user3100859 哦,我的错。看起来我没有正确读取所有错误消息。会回答的:)
标签: php html image file-upload upload