Home > other >  How I can apply color threshold into an image created from `imagecreatefromstring`?
How I can apply color threshold into an image created from `imagecreatefromstring`?

Time:07-19

I have the following piece of code:

define(RED_THESHOLD,100);
define(GREEN_THESHOLD,200);
define(BLUE_THESHOLD,100);

function thresholdImage(String $imgdata){
   $original_limit = ini_get('memory_limit');
   ini_set('memory_limit', '-1');
   $imageResource = imagecreatefromstring($imgData);

   // Limit red green and blue color channels here
}

But I do not know how I can apply the color the constants:

  • RED_THESHOLD
  • GREEN_THESHOLD
  • BLUE_THESHOLD

According to the classic algorithms I need to read pixel by pixel each channel and apply the threshold by the following piece of code (I use images red channel as an example):

 $new_pixel_value = ($red_pixel_value>RED_THESHOLD)?RED_THESHOLD:$red_pixel_value;

Do you know how I can do this?

CodePudding user response:

This can be done by finding the color index for each pixel, converting that into RGBA, then constraining those values, converting it back into a color index and setting the pixel.

<?php

const RED_THESHOLD = 255;
const GREEN_THESHOLD = 10;
const BLUE_THESHOLD = 10;

$image = imagecreatefrompng('test.png');

$maxX = imagesx($image);
$maxY = imagesy($image);

for ($y = 0; $y < $maxY;   $y) {
    for ($x = 0; $x < $maxX;   $x) {
        $existing = imagecolorsforindex($image, imagecolorat($image, $x, $y));

        $red = ($existing['red'] > RED_THESHOLD) ? RED_THESHOLD : $existing['red'];
        $green = ($existing['green'] > GREEN_THESHOLD) ? GREEN_THESHOLD : $existing['green'];
        $blue = ($existing['blue'] > BLUE_THESHOLD) ? BLUE_THESHOLD : $existing['blue'];

        $new = imagecolorexact($image, $red, $green, $blue);

        imagesetpixel($image, $x, $y, $new);
    }
}

imagepng($image, 'test2.png');

Here is a comparison picture: A picture of a rainbow with the above code applied and the output next to it

  • Related