I'd like to loop through each row and column in an image and replace certain pixels with different colors. I am open to a solution using GD or ImageMagick. Can anyone give me an example of how to do this? I've Googled several different ways and haven't found a solid example.
You can achieve this with GD by something like:
You will be handling colors as hex values
function replaceColor($img, $from, $to) {
$r = hexdec(substr($to, 0, 2));
$g = hexdec(substr($to, 2, 2));
$b = hexdec(substr($to, 4, 2));
// allocate $to color.
$to = imagecolorallocate($img, $r, $g, $b);
// pixel by pixel grid.
for ($y = 0; $y < imagesy($img); $y++) {
for ($x = 0; $x < imagesx($img); $x++) {
// find hex at x,y
$at = imagecolorat($img, $x, $y);
$r = 0xFF & ($at >> 0x10);
$g = 0xFF & ($at >> 0x8);
$b = 0xFF & ($at);
$hex = dechex($r).dechex($g).dechex($b);
// set $from to $to if hex matches.
if ($hex == $from) {
imagesetpixel($img, $x, $y, $to);
}
}
}
}
Related
I'm currently trying to get all pixel data inside of an image, and return it in JSON after encoding an Array. However, when I try to insert the $y data into the array, it always inserts 144. No in-between, always 144. When I echo $y, however, I get "0, 1, 2, etc."
$x, $r, $g, and $b are correct.
Any ideas? Here's my code:
<?php
header('Content-Type: application/json');
class PixelData {
private $ar = array(
"pixeldata" => [
]
);
public function getPixel($x, $y, $im) {
echo $y; // echoes "0, 1, 2, 3, etc."
global $ar;
$ar["pixeldata"][$x]["x"] = $x;
$ar["pixeldata"][$x]["y"] = $y;
$rgb = imagecolorat($im, $x, $y);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
$ar["pixeldata"][$x]["r"] = $r;
$ar["pixeldata"][$x]["g"] = $g;
$ar["pixeldata"][$x]["b"] = $b;
}
}
$src = "D:\Pictures\Test.png";
$im = imagecreatefrompng($src);
$size = getimagesize($src);
$width = imagesx($im);
$height = imagesy($im);
for($x = 0; $x < $width; $x++)
{
for($y = 0; $y < $height; $y++)
{
$pd = new PixelData();
$pd->getPixel($x, $y, $im);
}
}
$js = json_encode($ar);
echo $js;
?>
To elaborate further on my comment:
Your array is basically one-dimensional, because the only variable aspect is $ar['pixeldata'][$x]; you're never adding $y as another dimension. So, every time you increment $y in the inner-most for loop to go to the next level of $height you're overwriting the previous $x values. Basically, by the time your script is done, pixeldata will only contain the data of the top-most row of pixels, therefore they're always 144.
I also didn't notice until now, but if you wanted to store the data within the PixelData private array, you can't create a new instance within the for loops, you'd need to do that outside of the for loops.
This is probably what you want. As you can see, I've added an extra dimension to you pixeldata array, so as to include both $x and $y dimensions.
<?php
header('Content-Type: application/json');
class PixelData {
private $ar = array(
"pixeldata" => [
]
);
public function getPixel($x, $y, $im) {
echo $y; // echoes "0, 1, 2, 3, etc."
// Instantiate an array for this pixel
$this->ar["pixeldata"][$x][$y] = [];
$this->ar["pixeldata"][$x][$y]["x"] = $x;
$this->ar["pixeldata"][$x][$y]["y"] = $y;
$rgb = imagecolorat($im, $x, $y);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
$this->ar["pixeldata"][$x][$y]["r"] = $r;
$this->ar["pixeldata"][$x][$y]["g"] = $g;
$this->ar["pixeldata"][$x][$y]["b"] = $b;
}
public function getAr() {
return $this->ar;
}
}
$src = "D:\Pictures\Test.png";
$im = imagecreatefrompng($src);
$size = getimagesize($src);
$width = imagesx($im);
$height = imagesy($im);
$pd = new PixelData();
for($x = 0; $x < $width; $x++)
{
for($y = 0; $y < $height; $y++)
{
$pd->getPixel($x, $y, $im);
}
}
$js = json_encode($pd->getAr());
echo $js;
?>
There is an excellent answer on how to change the HUE of an image using PHP-GD library. But I need to know how to change the SATURATION of an image using PHP-GD. Here is a copy of the code from the answer which successfully changes the HUE of the image.
function imagehue(&$image, $angle) {
if($angle % 360 == 0) return;
$width = imagesx($image);
$height = imagesy($image);
for($x = 0; $x < $width; $x++) {
for($y = 0; $y < $height; $y++) {
$rgb = imagecolorat($image, $x, $y);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
$alpha = ($rgb & 0x7F000000) >> 24;
list($h, $s, $l) = rgb2hsl($r, $g, $b);
$h += $angle / 360;
if($h > 1) $h--;
list($r, $g, $b) = hsl2rgb($h, $s, $l);
imagesetpixel($image, $x, $y, imagecolorallocatealpha($image, $r, $g, $b, $alpha));
}
}
}
If you need to take a look at the code of helper functions rgb2hsl and hsl2rgb please check the original answer. Since Hue is one of the parameters of HSL, I thought I could modify the function somehow to get a working solution for Saturation. Despite of limited php skills I had to try but it did not work and produced bizarre results. Here is the modification that I am trying.
MODIFIED CODE: UPDATED as suggested by #mark
function imageSaturation(&$image, $saturationPercentage) {
$width = imagesx($image);
$height = imagesy($image);
for($x = 0; $x < $width; $x++) {
for($y = 0; $y < $height; $y++) {
$rgb = imagecolorat($image, $x, $y);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
$alpha = ($rgb & 0x7F000000) >> 24;
list($h, $s, $l) = rgb2hsl($r, $g, $b);
$s = $s * (100 + $saturationPercentage ) /100;
if($s > 1) $s = 1;
list($r, $g, $b) = hsl2rgb($h, $s, $l);
imagesetpixel($image, $x, $y, imagecolorallocatealpha($image, $r, $g, $b, $alpha));
}
}
}
header('Content-type: image/png');
$image = imagecreatefrompng('rgb.png');
imageSaturation($image, -80);//bring down current image saturation to 80%
imagepng($image);
EFFORTS UPDATE :
It has been pointed out to me by #Dai that these lines help construct a color code of an individual RGB pixel. So I guess this part can remained unchanged ?
$rgb = imagecolorat($image, $x, $y);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
$alpha = ($rgb & 0x7F000000) >> 24;
In the next line we are simply converting the RGB values to HSL with rgb2hsl($r, $g, $b); and assigning it to list($h, $s, $l). The point I am stuck at the moment are these lines.
$s += $saturationPercentage / 100;
if($s > 1) $s--;
I understand the syntax, but not sure how I handle these or if they are even required. If not an answer helpful hints / suggestions would be great. I am trying the code on this image to bring down the saturation from 100% to 80%, but I am getting this image as result.
I think you need something like
$s=$s * (100+$saturationPercentage)/100
else you are just adding a constant to each value rather than a percentage of the existing value.
Also, where you decrement 1 if your new saturation exceeds 1, you probaly would be better just setting it to 1.0, i.e. fully saturated like this:
if($s>1)$s=1
otherwise, say the resulting saturation is 1.3 (i.e. very, very saturated) you will make that into 0.3, i.e. very undersaturated, instead of 1.0 (fully saturated).
So, if $s is 0.7, and you add 10%, you will get
$s = 0.7 * (100 + 10)/100
$s = 0.7 * 1.1
$s = 0.77
I referred to answers on this question.
And I am currently using following code for hue overlay:
function imagehue(&$image, $angle) {
if($angle % 360 == 0) return;
$width = imagesx($image);
$height = imagesy($image);
for($x = 0; $x < $width; $x++) {
for($y = 0; $y < $height; $y++) {
$rgb = imagecolorat($image, $x, $y);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
$alpha = ($rgb & 0x7F000000) >> 24;
list($h, $s, $l) = rgb2hsl($r, $g, $b);
$h += $angle / 360;
if($h > 1) $h--;
list($r, $g, $b) = hsl2rgb($h, $s, $l);
imagesetpixel($image, $x, $y, imagecolorallocatealpha($image, $r, $g, $b, $alpha));
}
}
}
It works good with JPG. But this code doesn't work with transparent PNG images.
This is how I call this function for PNG images:
header('Content-type: image/png');
**$image = imagecreatefrompng('image.png');**
imagehue($image, 180);
imagejpeg($image);
Does anyone know what changes I should make?
It's because you use the imagejpeg function, use imagepng instead.
And if you also want it to work with alpha transparency, add this to your code:
imagealphablending($image, false);
imagesavealpha($image, true);
How can I check for a pixel pattern in PHP?
I mean I wanna use as condition that pixel A has xxx value and the following pixel B has another value yyy.
This is what I wrote:
$img = imagecreatefrompng("myimage.png");
$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 "#".$r.$g.$b.",";
$pixel = $r.$g.$b;
if ($pixel == "481023" and $pixel+1???
}
echo "<br />\r\n";
}
I'd like to ask also if I can speed up the whole thing by incrementing the $x value by 2 every for cycle. This because I have a pattern of 2 pixels, maybe I can use something like:
for($x=0;$x<$w;$x+2) {
//...
if ($pixel == "xxx") {//check the following pixel}
else if ($pixel == "yyy") {//check the previous pixel}
}
You might want to define a function like:
function getpixelat($img,$x,$y) {
$rgb = imagecolorat($img,$x,$y);
$r = dechex(($rgb >> 16) & 0xFF);
$g = dechex(($rgb >> 8) & 0xFF);
$b = dechex($rgb & 0xFF);
return $r.$g.$b;
}
Notice the dechex - you need this if you want it to look like an HTML colour code. Otherwise "white" would be 255255255 instead of ffffff and you'd also get ambiguous colours - is 202020 a dark gray (20,20,20) or "red with a slight hint of blue" (202,0,20)?
Once you have this, it should be a simple matter:
for( $y=0; $y<$h; $y++) {
for( $x=0; $x<$w; $x++) {
$pixel = getpixelat($img,$x,$y);
if( $pixel == "481023" && getpixelat($img,$x+1,$y) == "998877") {
// pattern! Do something here.
$x++; // increment X so we don't bother checking the next pixel again.
}
}
}
I want to load an entire image (PNG) into a 2-dimensional array where a black pixel is true and a white pixel is false.
What's the most efficient way of doing this?
Should I convert the image into bitmap and attempt to read that in, or is there a more efficient method?
This should do:
$image = imagecreatefrompng("input.png");
$width = imagesx($image);
$height = imagesy($image);
$colors = array();
for ($y = 0; $y < $height; $y++)
{
for ($x = 0; $x < $width; $x++)
{
$rgb = imagecolorat($image, $x, $y);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
$black = ($r == 0 && $g == 0 && $b == 0);
$colors[$x][$y] = $black;
}
}
A probably more efficient way would be using Imagick::exportImagePixels().