【问题标题】:How to make an Image to show only black text如何使图像仅显示黑色文本
【发布时间】:2017-10-05 11:55:43
【问题描述】:

我正在尝试执行以下操作: 我有一张图片,我想让只有用黑色书写的文本仍然可见,而其余的每种颜色都变得透明。

我尝试使用 PHP imagecolortransparent 函数执行此操作,但我无法弄清楚如何使其工作。 任何帮助都会很棒。 提前致谢

【问题讨论】:

  • 所以你想要一个完全透明的画布,上面只有一些黑色文本,没有其他内容?
  • 是的,我想用现有的图像来做这个

标签: php image-processing


【解决方案1】:

更新答案

必须有一个更简单的方法,但在我想到之前,这应该可行:

// Read original image
$start = imagecreatefrompng("input.png");

// Make true colour image same size
$im = imagecreatetruecolor(imagesx($start),imagesy($start));
$transparent = imagecolorallocatealpha($im, 0, 0, 0, 127);
$red=imagecolorallocate($im,255,0,0);
imagesavealpha($im, TRUE);

// Fill the new image with transparency
imagefill($im, 0, 0, $transparent);

// Copy only black pixels across from original to new
for($x=0;$x<imagesx($im);$x++){
   for($y=0;$y<imagesy($im);$y++){
      $rgb = imagecolorat($start,$x,$y);
      if($rgb==0){
         imagesetpixel($im,$x,$y,$black);
      }
   }
}
imagepng($im,"result.png");

原答案

我会这样做:

// Read original image
$start   = imagecreatefrompng("input.png");

// Create a proper truecolour image the same size that can support transparency
$im = imagecreatetruecolor(imagesx($start),imagesy($start));
$transparent = imagecolorallocatealpha($im, 0, 0, 0, 127);
imagefill($im, 0, 0, $transparent);
imagesavealpha($im, TRUE);
$black = imagecolorallocate($im, 0, 0, 0);
$text="This is some quite black text";
imagestring($im,5,0,75,$text,$black);
imagepng($im,"result.png");

input.png

result.png

【讨论】:

  • 感谢您的回复,对于不清楚的地方我深表歉意。我有一个已经包含黑色文本的输入图像。
  • 请再看看 - 我已经改变了答案。
  • 非常感谢马克,它看起来仍然可以解决我的问题,如果我需要任何帮助,我会联系你。抱歉,我没有足够的代表来支持你的答案。
  • 如果它适合您,您可以稍后接受它(通过单击投票记录旁边的空心对勾/复选标记)。如果您的文本使用几乎黑色的颜色进行抗锯齿处理,您可能需要更改以if(...) 开头的行,因为我的代码正好找到黑色像素。您将知道您的文本是否看起来参差不齐。只要问是不是。
猜你喜欢
  • 1970-01-01
  • 2018-07-18
  • 2014-06-09
  • 2019-12-16
  • 2022-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多