在 PHP 中调整图像大小
2022-08-30 07:22:23
我想编写一些PHP代码,自动将通过表单上传的任何图像的大小调整为147x147px,但我不知道如何去做(我是一个相对的PHP新手)。
到目前为止,我已经成功上传了图像,识别了文件类型并清理了名称,但我想将调整大小功能添加到代码中。例如,我有一个尺寸为2.3MB的测试图像,尺寸为1331x1331,我希望代码将其缩小,我猜这也将大大压缩图像的文件大小。
到目前为止,我有以下几点:
if ($_FILES) {
//Put file properties into variables
$file_name = $_FILES['profile-image']['name'];
$file_size = $_FILES['profile-image']['size'];
$file_tmp_name = $_FILES['profile-image']['tmp_name'];
//Determine filetype
switch ($_FILES['profile-image']['type']) {
case 'image/jpeg': $ext = "jpg"; break;
case 'image/png': $ext = "png"; break;
default: $ext = ''; break;
}
if ($ext) {
//Check filesize
if ($file_size < 500000) {
//Process file - clean up filename and move to safe location
$n = "$file_name";
$n = ereg_replace("[^A-Za-z0-9.]", "", $n);
$n = strtolower($n);
$n = "avatars/$n";
move_uploaded_file($file_tmp_name, $n);
} else {
$bad_message = "Please ensure your chosen file is less than 5MB.";
}
} else {
$bad_message = "Please ensure your image is of filetype .jpg or.png.";
}
}
$query = "INSERT INTO users (image) VALUES ('$n')";
mysql_query($query) or die("Insert failed. " . mysql_error() . "<br />" . $query);