3

我正在尝试允许在我的网站上上传透明的个人资料图片(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 只是为了测试:

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

在此处输入图像描述

我试图保留透明度信息,但它似乎不起作用。我做的不对吗?

提前致谢。

4

1 回答 1

4

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

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

你也可以检查这个问题

于 2012-08-12T06:18:29.713 回答