gpt4 book ai didi

php - 为什么即使我设置了 alpha 混合设置,GIF 图像也会失去 imagegif() 的透明度?

转载 作者:行者123 更新时间:2023-12-01 23:33:57 24 4
gpt4 key购买 nike

我正在尝试允许在我的网站上上传透明个人资料图片(PNG 和 GIF),因为有时用户上传透明个人资料图片并且透明区域变黑会很烦人。问题是即使在使用 imagealpha*() 函数后透明度仍然会丢失。

我确实意识到还有其他问题,但这些问题的答案对我不起作用。

这是我的代码:

// [...]

switch(strtolower($_FILES['picture']['type'])) {
case 'image/jpeg':
$image = imagecreatefromjpeg($_FILES['picture']['tmp_name']);
break;
case 'image/png':
$image = imagecreatefrompng($_FILES['picture']['tmp_name']);
break;
case 'image/gif':
$image = imagecreatefromgif($_FILES['picture']['tmp_name']);
break;
default:
msg('Sorry, but the type of file that you selected is not allowed. We only allow JPEG, PNG, and GIF.','error');
header("Location: /settings/profile");
exit;
}

// Target dimensions
$max_width = 143;
$max_height = 143;

// Get current dimensions
$old_width = imagesx($image);
$old_height = imagesy($image);

// Calculate the scaling we need to do to fit the image inside our frame
$scale = min($max_width/$old_width, $max_height/$old_height);

// Get the new dimensions
$new_width = ceil($scale*$old_width);
$new_height = ceil($scale*$old_height);

// Create new empty image
$new = imagecreatetruecolor($new_width, $new_height);

// Resize old image into new
imagecopyresampled($new, $image, 0, 0, 0, 0, $new_width, $new_height, $old_width, $old_height);
$file_name = 'avatar_'.randString(20).mt_rand(111,999).'.'.str_replace('image/','',$_FILES['picture']['type']);

switch(strtolower($_FILES['picture']['type'])) {
case 'image/jpeg':
$img = imagejpeg($new, 'user/uploads/'.$file_name, 95);
break;
case 'image/png':
imagealphablending($new, false);
imagesavealpha($new, true);
$img = imagepng($new, 'user/uploads/'.$file_name, 95);
break;
case 'image/gif':
imagealphablending($new, false);
imagesavealpha($new, true);
$img = imagegif($new, 'user/uploads/'.$file_name);
break;
}

imagedestroy($image);
imagedestroy($new);

if($img) {
$dbUpdate = mysql_query("UPDATE users SET user_pic = '$file_name' WHERE uid = $userid");
}

if($img && $dbUpdate) {
msg("Your profile picture has been changed successfully.","success");
header("Location: /settings/profile");
exit;
}

// [...]

我尝试上传这个 GIF 只是为了测试:

但是上传后就失去了透明度:

enter image description here

我试图用它保留透明度信息,但它似乎不起作用。我做错了什么吗?

提前致谢。

最佳答案

创建透明色并在复制前用该颜色填充$new 图像。如果您不这样做,新图像的背景颜色将默认为黑色。

$new = imagecreatetruecolor($new_width, $new_height); 
$transparent = imagecolorallocatealpha($new, 0, 0, 0, 127);
imagefill($new, 0, 0, $transparent);
imagealphablending($new, true);

你也可以查看这个question

关于php - 为什么即使我设置了 alpha 混合设置,GIF 图像也会失去 imagegif() 的透明度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11912077/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com