【发布时间】:2011-11-11 05:36:48
【问题描述】:
我在 php 中有一个用户配置文件,我想让用户选择更改他们的配置文件图片。但是当他们通过 $_POST 提交新图片时,我希望将图片调整为:
高度:110px |宽度:与高度有关(如果宽度大于高度)
宽度:110px |高度:与宽度有关(如果高度大于宽度)
调整大小完成后,我想裁剪图片,使其变为 110px x 110px,但我希望它居中。
例如,如果用户上传的图片宽度为 110px,高度为 200px(调整大小后的尺寸),则裁剪后的新图像将从右侧裁剪 110x110 90px。我想要的是从左侧裁剪 45px,从右侧裁剪另外 45px,以便居中
该函数将接受 .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;
}
【问题讨论】:
标签: php image-processing file-upload resize crop