Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through all the pixels of an image?

Tags:

php

gd

I want to loop through all the pixels of an image, find the rgba value of that pixel, and do something with those pixels.

Example

Say I have an image that's 100x100 pixels. I want to find the value of each one of those pixels with the function I already made:

function getPixel($image, $x, $y) {

  $colors = imagecolorsforindex($image, imagecolorat($image, $x, $y));
  $inrgba = 'rgba(' . $colors['red'] . ',' . $colors['green'] . ',' . $colors['blue'] . ',' . $colors['alpha'] . ')';
  return $inrgba;
}

And store those values, along with the dimensions of the image, in an array, or an array of arrays. I want to use the end result in a html page.

How do I do this?

like image 602
PitaJ Avatar asked May 15 '12 03:05

PitaJ


2 Answers

for($x=1;$x<=$width;$x++)
{
    for($y=1;$y<=$height;$y++)
    {
        $pixel=getPixel($image, $x, $y);
        //do something
    }
}

What this will do is find each pixel in each column.

i=iteration
pixel coordinate = (x,y)

For a 5 x 5 image the iteration would look like this:

i1 = (1,1)
i2 = (1,2)
i3 = (1,3)
i4 = (1,4)
i5 = (1,5)
i6 = (2,1)
i7 = (2,2)
i8 = (2,3)
i9 = (2,4)
i10 = (2,5)
i11 = (3,1)
i12 = (3,2)
i13 = (3,3)
i14 = (3,4)
i15 = (3,5)
i16 = (4,1)
i17 = (4,2)
i18 = (4,3)
i19 = (4,4)
i20 = (4,5)
i21 = (5,1)
i22 = (5,2)
i23 = (5,3)
i24 = (5,4)
i25 = (5,5)
like image 199
bluegman991 Avatar answered Sep 21 '22 08:09

bluegman991


Here's the complete answer, without the out of bounce error

<?php

    $src    = '2fuse.jpg';
    $im     = imagecreatefromjpeg($src);
    $size   = getimagesize($src);
    $width  = $size[0];
    $height = $size[1];

    for($x=0;$x<$width;$x++)
    {
        for($y=0;$y<$height;$y++)
        {
            $rgb = imagecolorat($im, $x, $y);
            $r = ($rgb >> 16) & 0xFF;
            $g = ($rgb >> 8) & 0xFF;
            $b = $rgb & 0xFF;
            var_dump($r, $g, $b);
        }
    }
like image 32
PauAI Avatar answered Sep 21 '22 08:09

PauAI