我在php中有一个用户配置文件,我想让用户选择更改他们的个人资料图片。但是,当他们通过$ _POST提交他们的新照片时,我想将照片的大小调整为:php在上传后调整图像大小并将其裁剪到中心
height:110px |宽度:与高度有关(如果宽度大于高度)
width:110px |高度:与宽度有关(如果高度大于宽度)
当调整大小完成后,我想剪裁图片使其变为110px x 110px,但我希望它居中。
例如,如果用户上传110px宽度和200px高度(调整大小后的尺寸)的图片,裁剪后的新图像将从右侧裁剪90x 110x110。我想是从左边,另一个×45像素从右边冒出×45像素,因此将居中
功能将接受.png
,.gif
和.jpg
图像,将保存新的图像仅在jpg格式不管初始格式为。
我搜索了很多创建这样一个功能,我发现了一个答案,但任何时候我试图改变一些小的细节,一切都停止正常工作。
我迄今为止代码:
<?php
$userfile_name = $_FILES["sgnIMG"]["name"];
$userfile_tmp = $_FILES["sgnIMG"]["tmp_name"];
$userfile_size = $_FILES["sgnIMG"]["size"];
$filename = basename($_FILES["sgnIMG"]["name"]);
$file_ext = substr($filename, strrpos($filename, ".") + 1);
$large_image_location = $target_path . $filename;
$ext = '';
if ($file_ext == 'jpg') {
$ext = 1;
} else if ($file_ext == 'gif') {
$ext = 2;
} else if ($file_ext == 'png') {
$ext = 3;
} else {
$ext = 0;
}
$target = $target_path . basename($_FILES["sgnIMG"]["name"]);
if (move_uploaded_file($userfile_tmp, $target)) {
$newImg = resize110($target, $ext);
if (isset($_POST['imupd']) && ($_POST['imupd'] == 'up')) {
$sql = "UPDATE users SET avatar='" . str_replace('im/users/', '', $newImg) . "' WHERE id=" . $_SESSION['sesID'] . "";
$result = mysql_query($sql);
if ($result) {
echo '<img src="' . $newImg . '" width="110" title="' . $file_ext . '"/>';
} else {
echo '<img src="im/avatars/px.png" width="110" title="' . $file_ext . '"/>';
}
}
} else {
}
function getHeight($image)
{
$sizes = getimagesize($image);
$height = $sizes[1];
return $height;
}
function getWidth($image)
{
$sizes = getimagesize($image);
$width = $sizes[0];
return $width;
}
function resize110($image, $ext)
{
chmod($image, 0777);
$oldHeight = getHeight($image);
$oldWidth = getWidth($image);
if ($oldHeight < $oldWidth) {
$newImageHeight = 110;
$newImageWidth = ceil((110 * $oldWidth)/$oldHeight);
imagecopyresampled($newImage, $source, -ceil(($newImageWidth - 110)/2), 0, 0, 0, $newImageWidth, $newImageHeight, $oldWidth, $oldHeight);
} else {
$newImageHeight = ceil((110 * $oldHeight)/$oldWidth);
$newImageWidth = 110;
imagecopyresampled($newImage, $source, 0, -ceil(($newImageHeight - 110)/2), 0, 0, $newImageWidth, $newImageHeight, $oldWidth, $oldHeight);
}
$newImage = imagecreatetruecolor(110, 110);
chmod($image, 0777);
return $image;
switch ($ext) {
case 1;
$source = imagecreatefromjpeg($image);
break;
case 2;
$source = imagecreatefromgif($image);
break;
case 3;
$source = imagecreatefrompng($image);
break;
}
imagejpeg($newImage, $image, 90);
return $image;
}