How to remove all colours that not X color?

IMagick is a native PHP extension to create and modify images using the ImageMagick API. ImageMagick Studio LLC did not write nor does it maintain the IMagick extension, however, IMagick users are welcome to discuss the extension here.
Post Reply
lopes_andre

How to remove all colours that not X color?

Post by lopes_andre »

Hi,

I need to remove colours or an image. For example, I need to remove all non BLUE colours. How can I achieve this?

I have this code to go pixel by pixel on the selected image:

Code: Select all

<?php
   $img = imagecreatefromjpeg("img.jpg");
  
   $w = imagesx($img);
   $h = imagesy($img);
  
   for($y=0;$y<$h;$y++) {
      for($x=0;$x<$w;$x++) {
         $rgb = imagecolorat($img, $x, $y);
         $r = ($rgb >> 16) & 0xFF;
         $g = ($rgb >> 8) & 0xFF;
         $b = $rgb & 0xFF;        
         echo "#".str_repeat("0",2-strlen(dechex($r))).dechex($r).
              str_repeat("0",2-strlen(dechex($g))).dechex($g).
              str_repeat("0",2-strlen(dechex($b))).dechex($b).",";
      }
      echo "<br />\r\n";
   }
?>


Any ideas on how to achieve this?

Best regards,
Bonzo
Posts: 2971
Joined: 2006-05-20T08:08:19-07:00
Location: Cambridge, England

Re: How to remove all colours that not X color?

Post by Bonzo »

Are you sure you want to do this with Imagick or using php exec() ?

What do the colours removed become e.g. Transparent ?

This is an image I made a few years ago changing all non green pixels to gray:
Image

Code: Select all

<?php
// Create a new image with everything transparent apart from the selected colour. 
// This image must be saved as a png due to the transparency.
exec("convert $img -matte \( +clone -fuzz 20% -transparent rgb\(38,134,71\) \) -compose DstOut -composite temp.png");

// Another tempory image is made from the original but completely grey.
exec("convert $img -colorspace Gray grey_background.jpg"); 

// The two images are combined and flattened into one image.
exec("convert grey_background.jpg -page +0+0 temp.png -flatten output.jpg");
 
// The tempory images are deleted.
unlink ('output_hat.png');
unlink ('grey_background.jpg');
?>
The code is quite old and could probably be improved.
Post Reply