简体   繁体   中英

How to make an Image to show only black text

I am trying to do the following: I Have a picture I want to make that only text which is written in black remains visible and rest of every colour gets transparent.

I tried to do this using PHP imagecolortransparent function but I am not able to figure out how to make it work. Any help will be great. Thanks In advance

Updated Answer

There must be an easier way, but until I think of it, this should work:

// 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");

Original Answer

I would do this:

// 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

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM