【问题标题】:Convert non-transparent pixels to black将不透明像素转换为黑色
【发布时间】:2011-03-26 11:01:49
【问题描述】:

我正在寻找一种将图像转换为使所有非透明像素(具有 alpha != 1 的像素)变为黑色和透明像素不受影响(或转换为白色)的方法。我得到的最接近的是下面的 imagemagick 命令:

convert <img> -colorspace Gray <out>

但是这仍然给了我一些灰色而不是完全的黑色。我已经尝试了所有色彩空间选项,但没有一个能胜任。

知道如何使用 imagemagick 或类似工具(或使用 PHP 库,如果存在)来实现这一点

【问题讨论】:

    标签: php image-processing imagemagick


    【解决方案1】:

    我知道这个问题很老,但现在我偶然发现了它,我不妨回答一下。

    你想要的 ImageMagick 命令是:

    convert <img> -alpha extract -threshold 0 -negate -transparent white <out>
    

    我也会分解它在做什么。

    1. -alpha extract - 获取图像的 alpha 蒙版。完全透明的像素为黑色,完全不透明的像素为白色。
    2. -threshold 0 - 如果所有通道大于零,则将它们增加到最大值。在这种情况下,它将将除完全黑色的像素之外的每个像素都设为白色。
    3. -negate - 反转图像。现在我们的黑人是白人,我们的白人是黑人。
    4. -transparent white - 将白色像素设置为透明。如果您希望原本透明的像素为白色,则可以排除这种情况。

    之前

    之后

    【讨论】:

      【解决方案2】:

      嗯,你可以用 GD 和一对循环来做到这一点:

      $img = imagecreatefromstring(file_get_contents($imgFile));
      $width = imagesx($img);
      $hieght = imagesy($img);
      
      $black = imagecolorallocate($img, 0, 0, 0);
      $white = imagecolorallocate($img, 255, 255, 255);
      
      for ($x = 0; $x < $width; $x++) {
          for ($y = 0; $y < $width; $y++) {
              $color = imagecolorat($img, $x, $y);
              $color = imagecolorforindex($color);
              if ($color['alpha'] == 1) {
                  imagesetpixel($img, $x, $y, $black);
              } else {
                  imagesetpixel($img, $x, $y, $white);
              }
          }
      }
      

      或者,您可以替换颜色(这可能有效,也可能无效):

      $img = imagecreatefromstring(file_get_contents($imgFile));
      $maxcolors = imagecolorstotal($img);
      for ($i = 1; $i <= $maxcolors; $i++) {
          $color = imagecolorforindex($i);
          if ($color['alpha'] == 1) {
              imagecolorset($img, $i, 0, 0, 0);
          } else {
              imagecolorset($img, $i, 255, 255, 255);
          }
      }
      

      【讨论】:

        【解决方案3】:

        我不确定它是否会对您有所帮助(即所提供的方法是否会单独留下透明像素),但请查看此问题的答案:PHP/ImageMagic Get the “shadow” of an image

        【讨论】:

          猜你喜欢
          • 2012-07-30
          • 1970-01-01
          • 1970-01-01
          • 2016-06-14
          • 1970-01-01
          • 2013-04-29
          • 2021-10-20
          • 2013-01-09
          • 2013-08-21
          相关资源
          最近更新 更多