1

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?

3
  • And what if its not black or white? Commented Nov 23, 2011 at 10:59
  • It is always black or white, it's a 2bit bitmap. Commented Nov 24, 2011 at 5:35
  • Note: A black&white bitmap is 1-bit, because you only need 1 bit of information (black or white) for each pixel. Commented Jun 3, 2014 at 16:26

1 Answer 1

4

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().

Sign up to request clarification or add additional context in comments.

5 Comments

I know about imagecolorat(), and I'm looking for something more efficient. But thank you for your answer.
@Alasdair you didn't mention that in your question. If you have ImageMagick, you can take a look at exportImagePixels() and loop through that array.
Sorry, I should have explained in more detail. The whole reason I want to do this is to bypass GD.
@Alasdair how much of GD do you want to bypass? You want to decode PNG in pure PHP? You want an offline task outside PHP?
I was planning to convert the PNG to bitmap and read this into an array, completely bypassing GD. But I've given up now. This answer here is technically correct, and I didn't phrase my question very well, so I will accept.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.