B. Schmidt
B. Schmidt

Reputation: 83

Editing image colors in PHP - color exchange

To specifically describe my problem, I am trying to convert all colors that are close to black - within a threshold - to completely black. For example, in RGB terms, colors with all components less than 50 become (0,0,0). I know this can be done in GIMP per the link below but does anybody know of a way this can be done in PHP?

https://askubuntu.com/questions/27578/in-gimp-can-i-change-all-black-pixels-in-a-picture-to-blue-pixels

Upvotes: 3

Views: 2380

Answers (2)

Mark Setchell
Mark Setchell

Reputation: 207853

I'm no PHP programmer, but it would look something like this:

#!/usr/local/bin/php -f

<?php
$im = imagecreatefrompng("image.png");
$black = imagecolorallocate($im,0,0,0); 
$w = imagesx($im); // image width
$h = imagesy($im); // image height
for($x = 0; $x < $w; $x++) {
   for($y = 0; $y < $h; $y++) {
      // Get the colour of this pixel
      $rgb = imagecolorat($im, $x, $y);

      $r = ($rgb >> 16) & 0xFF;
      if($r>=50)continue;         // Don't bother calculating rest if over threshold

      $g = ($rgb >> 8) & 0xFF;
      if($g>=50)continue;         // Don't bother calculating rest if over threshold

      $b = $rgb & 0xFF;
      if($b>=50)continue;         // Don't bother calculating rest if over threshold

      // Change this pixel to black
      imagesetpixel($im,$x,$y,$black);
   }
}
imagepng($im,"result.png");
?>

Which converts this

enter image description here

to this

enter image description here

Upvotes: 0

Scalable
Scalable

Reputation: 1681

You can use GD library to read and set a pixel color in an image. The exact algorithm and threshold are up to you.

Read a Pixel

Set a pixel

Upvotes: 0

Related Questions