17

I need to use PHP to read every pixel in a image. It's for graphical password project. When user chooses a password, they will select some area on the image. and I'm trying to do it by pixel value. Is it possible??

2 Answers 2

33

Yes, you can get the pixel "value" as in color using imagecolorat().

$color = imagecolorat($resource, $x, $y);

Where $resource is your image resource, and $x, $y are the coordinates of the pixel you want to get the color of.

You can iterate through all of the pixels like this. Note that this can be an expensive task depending on how large the image is.

$width = imagesx($resource);
$height = imagesy($resource);

for($x = 0; $x < $width; $x++) {
    for($y = 0; $y < $height; $y++) {
        // pixel color at (x, y)
        $color = imagecolorat($resource, $x, $y);
    }
}
2
  • 7
    Notice that this may return either 1) the index of color at that pixel 2) actual color at that pixel. If You use imagecolorsforindex(), You can be sure that You get RGB values. Commented Dec 23, 2015 at 22:16
  • @GintareStatkute the string as in the image path? Commented May 14, 2017 at 3:16
0

@GintareStatkute If you have the image content as a string you can use:

<?php
$data = 'iVBORw0KGgoAAAANSUhEUgAAABwAAAASCAMAAAB/2U7WAAAABl'
   . 'BMVEUAAAD///+l2Z/dAAAASUlEQVR4XqWQUQoAIAxC2/0vXZDr'
   . 'EX4IJTRkb7lobNUStXsB0jIXIAMSsQnWlsV+wULF4Avk9fLq2r'
   . '8a5HSE35Q3eO2XP1A1wQkZSgETvDtKdQAAAABJRU5ErkJggg==';
$data = base64_decode($data);
$im = imagecreatefromstring($data);

If you have the file path instead, then use any of the creation functions, such as imagecreatefromgif(), imagecreatefromjpeg(), imagecreatefrompng().

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.