【问题标题】:PHP: How to make a green area (background) in an image transparent?PHP:如何使图像中的绿色区域(背景)透明?
【发布时间】:2012-04-08 18:49:30
【问题描述】:

我是 Stackoverflow 的新手。

我非常想弄清楚是否可以使用 PHP 脚本使图像的特定颜色透明。如果是的话,如何去做。

假设这是背景颜色(绿色)必须完全透明的图像:French Hotdog w/ green background

我完全不知道这样的脚本会是什么样子,甚至不知道从哪里开始。 我想您可能必须设置不需要的 RGB 颜色,然后“扫描”图像中的每个像素以确定哪些像素必须是透明的。但除此之外,我一无所知。

真心希望这里有人能够帮助我解决这个问题。

【问题讨论】:

  • 嗨@Ace,这个网站是关于具体的编程问题的。你写你不知道开始。然后先做功课,找到至少一条线索,例如颜色(提示)。然后开始编写代码,然后突出显示您遇到障碍的地方。

标签: php image background transparent


【解决方案1】:

首先图片应该是 png 因为 jpeg 不支持透明度然后代码是这样的:

<?php
   $image = 'test.png';
   $im = imagecreatefrompng($image); 
   //if you exactly know the RGB color indexes
   //$rgb = imagecolorexact($im, 0, 0, 0);
   //or keep the rgb color by position so at top 0 left 0
   $rgb = imagecolorat($im, 0, 0);
   imagecolortransparent($im, $rgb);
   header("Content-type: image/png");
   //display the image directly
   imagepng($im);
   // or save it
   // imagepng($im, 'test-to-transparent.png');
   imagedestroy($im); 
?>

【讨论】:

  • 辉煌的aSeptik! :) 感谢脚本中的 cmets - 真的很有帮助。现在我只是在想是否有办法让图像中的每个绿色像素都透明,无论颜色的阴影、色调、饱和度或亮度如何。这似乎是完全“删除”背景颜色的唯一方法。关于如何做到这一点的任何想法?
【解决方案2】:

imagecolortransparent() 会帮助你:

...
$yourColor = imagecolorallocate($im, 0, 0, 0);
imagecolortransparent($im, $yourColor);
...

【讨论】:

  • 非常感谢 Narek,这很有意义。不过,恐怕我需要一些帮助才能将图像的像素扫描为 $yourColor。
猜你喜欢
  • 2011-07-06
  • 2022-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多