我正在努力创建一个处理头像上传的功能。 我的问题是,当我上传透明图像时,它会在我调整大小后将所有透明的黑色变为黑色。
我尝试过使用imagesavealpha()& imagealphablending()选项,但背景仍然变黑。
可能只是我是盲人而没有在代码中看到问题,但我不知道为什么会这样做。
我可以确认,在上传后将图像移动到图像/头像文件夹后,背景仍然是透明的。
这是我目前的代码,我一直在测试.png图片:
function upload_avatar(){
$base_path = SYSTEM_PATH;
if($_FILES['avatar_img']['tmp_name'] != '') {
$id = md5($this->user_id());
$filename = $_FILES['avatar_img']['name'];
$file_basename = substr($filename, 0, strripos($filename, '.')); // strip extention
$file_ext = substr($filename, strripos($filename, '.')); // strip name
$filesize = $_FILES['avatar_img']['size'];
$newfilename = $id . $file_ext;
if ($file_ext == ".jpg" || $file_ext == ".JPG" || $file_ext == ".jpeg" || $file_ext == ".png" || $file_ext == ".gif"){
if($filesize <= 153600){
move_uploaded_file($_FILES['avatar_img']['tmp_name'], $base_path."/images/avatars/" . $newfilename);
//resize image form
list($width, $height) = getimagesize($base_path."/images/avatars/" . $newfilename);
$scale_height = $height/$width;
$scale_width = $width/$height;
//Find height and width of the image
if($width > $height && $width > 150){
$width_new = 150;
$height_new = round($width_new*$scale_height);
}else if($height > $width && $height > 150){
$height_new = 150;
$width_new = round($height_new*$scale_width);
}else{
$height_new = $height;
$width_new = $width;
}
switch($file_ext) {
case ".jpg" :
case ".jpeg":
$source = imagecreatefromjpeg($base_path."/images/avatars/" . $newfilename);
break;
case ".png" :
$source = imagecreatefrompng($base_path."/images/avatars/" . $newfilename);
break;
default:
$source = imagecreatefromgif($base_path."/images/avatars/" . $newfilename);
break;
}
$destination = imagecreatetruecolor($width_new, $height_new);
imagesavealpha($destination, true);
imagealphablending($destination, true);
imagecopyresized($destination, $source, 0, 0, 0, 0, $width_new, $height_new, $width, $height);
switch($file_ext) {
case ".jpg":
case ".jpeg":
imagejpeg($destination, $base_path."/images/avatars/" . $newfilename, 85);
break;
case ".png":
imagepng($destination, $base_path."/images/avatars/" . $newfilename, 8);
break;
default:
imagegif($destination, $base_path."/images/avatars/" . $newfilename, 85);
break;
}
return $newfilename;
}else{
$this->upload_avatar = '<br />But the avatar was not updated. The avatar\'s size exceeded the 150kb limit. ';
return '';
}
}else{
$this->upload_avatar = '<br />But the avatar was not updated. The avatar must be one of the following formats: jpg, jpeg, png or gif. ';
return '';
}
}else{
return '';
}
}
任何帮助都会受到赞赏,因为我现在很难看到这一点。
谢谢!