Home > Net >  PHP get the newly added color from image at specific pixel range
PHP get the newly added color from image at specific pixel range

Time:11-29

I created a PHP code to add color at specific pixel range for example x=0,y=0 to x=24, y=0. This creates a straight line on top left corner of the image towards y axis. Now beofre closing the image if I try to read the color from those position it returns me the color I added. But if i reopen the image and try to read the color from those pixels it is not giving me the exact color I added instead it give a color close to it. I am adding the piece of code which I used:

`$canvas = imagecreatefromjpeg('first_frame.jpg');

//create a random color

$rand = str_pad(dechex(rand(0x000000, 0xFFFFFF)), 6, 0, STR_PAD_LEFT);
$dec_color= hexdec($rand);

for ($i=0; $i < 24; $i  ) { 
  imagerectangle($canvas,$i,0,0,0, $dec_color);
 }

//read the image pixels add

for ($x=0; $x < 24 ; $x  ) { 
  echo $new_color= imagecolorat($canvas, $x, 0);
  echo '<br>';

}

$filename = 'test/'.time().'.jpg';

//store the image in dir

imagejpeg($canvas, $filename);

//destroy the opened image

imagedestroy($canvas);`

The above code gives me tha random generated color, adds it to the image and then reads those added colors. So this code gives me the expected added colors. If i add the following code after the function imagedestroy($canvas), it gives me some other colors close to the one added.

`$dimg = imagecreatefromjpeg($filename);
for ($x=0; $x < 24 ; $x  ) { 
  echo $new_color= imagecolorat($dimg, $x, 0);
  echo '<br>';

}
`

I need to extract the exact color added to the image after the image is stored.

Added color and extracted colors are here

CodePudding user response:

Thanks a lot for your help CBroe. So here is the complete code for getting the exact pixel color added in an image and it is unchanged after shared and retrived via multiple social media platforms. This may someone in future.

<?php

// load teh image

$canvas = imagecreatefromjpeg('first_frame.jpg');

// create a random color
$rand = str_pad(dechex(rand(0x000000, 0xFFFFFF)), 6, 0, STR_PAD_LEFT);
$dec_color= hexdec($rand);

echo 'color created and added: '.$dec_color;
// add the new color to image

for ($i=0; $i < 24; $i  ) { 
   imagesetpixel($canvas,$i,0,$dec_color);
}

// store the image and close the file opened

$filename = 'test/output.png'; 

imagepng($canvas, $filename);

imagedestroy($canvas);

// now read the same file stored and get the color ranges to be stored

$dimg = imagecreatefrompng($filename);

$extracted_color = array();

for ($x=0; $x < 24 ; $x  ) { 
  $extracted_color[]= imagecolorat($dimg, $x, 0);
}

echo "<br>Retrived colors:<pre>".print_r($extracted_color,1)."</pre>";

imagedestroy($dimg);
?>
  • Related