0
我正在嘗試做一個函數來處理頭像上傳。 我的問題是,當我上傳一個透明的圖像,它調整後,它把所有透明的黑色。上傳透明圖片添加黑色背景
我試過使用imageavephapha()& 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 '';
}
}
任何幫助,因爲我要瘋了這個現在正在尋找可以理解的。
謝謝!
乾杯,會給它看看:)。我之前使用過該功能,但我認爲使用上述方法也是可行的。我顯然是錯的。 謝謝,如果沒有人能告訴我我的初始代碼有什麼問題,請試試看。 謝謝! – MrE 2012-02-04 21:11:25
我將它轉換爲使用您鏈接的功能。猜我會去那(工作)。謝謝! – MrE 2012-02-04 21:21:59