【问题标题】:Black background when turning a PNG into a GIF将 PNG 转换为 GIF 时的黑色背景
【发布时间】:2011-07-04 05:33:27
【问题描述】:

我尝试打开一个 PNG 图像,然后将其输出为 GIF 图像。但是,当我这样做并且背景变黑时,透明度会丢失。如果我将图像输出为 PNG,它可以工作,但我特别需要将图像打开为 PNG 并将其输出为 GIF。

这是我目前所拥有的:

 <?php
 header("Content-type: image/gif");

 $new_img = imagecreatefrompng($image);
 imagealphablending($new_img, false); 
 imagesavealpha($new_img, true); 
 imagegif($new_img);
 ?>

然而,imagepng($new_img) 会保存背景透明度,但不会输出为 GIF。

【问题讨论】:

  • 哦,如果我首先将图像创建为 gif 并执行此操作,它就可以正常工作。所以这不是我的浏览器。从 PNG 到 GIF 的转换搞砸了。
  • @sombe - “大多数主流浏览器不支持 GIF 透明”,我认为自 1800 年以来的所有浏览器都支持 GIF 透明。

标签: php


【解决方案1】:

试试这个代码:

<?php
header("Content-type: image/gif");

$new_img = imagecreatefrompng($image);
$trans_color = imagecolortransparent($new_img);
$trans_index = imagecolorallocate($new_img, $trans_color['red'], $trans_color['green'], $trans_color['blue']);
imagecolortransparent($new_img, $trans_index);
imagegif($new_img);
?>

【讨论】:

  • 这似乎也不起作用。我认为主要问题是从 PNG 到 GIF 的转换,所以也许有办法将图像更改为 GIF,然后在将整个图像输出到浏览器之前弄乱透明度。
【解决方案2】:

所以我设法让它工作。如果有人有更好的解决方案,请告诉我:

 <?php
  header("Content-type: image/gif");

  $new_img = imagecreatefrompng($image);
  $background = imagecreatefrompng("background.png");
  imagecopyresampled($background, $new_img, 0, 12, 0, 0, 100, 125, 100, 125);
  $c = imagecolorat($background, 0, 0);
  imagefilledrectangle($background, 0, 112, 100, 125, $c);
  imagecolortransparent($background, $c);
  imagegif($new_img);
  ?>

【讨论】:

    猜你喜欢
    • 2016-01-12
    • 2011-09-24
    • 2013-04-23
    • 1970-01-01
    • 2015-12-31
    • 1970-01-01
    • 2019-12-13
    • 1970-01-01
    • 2015-03-26
    相关资源
    最近更新 更多