Page 1 of 1

How to remove all colours that not X color?

Posted: 2010-07-19T08:28:41-07:00
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,

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

Posted: 2010-07-19T08:47:47-07:00
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.