Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert an image into digits with PHP?

Tags:

php

image

I am trying to figure out how I can convert a color image into numbers.

For example, if I have an image like the one shown in figure (b), how can I get a output like figure (a) in to a text file?

enter image description here

like image 999
Justin k Avatar asked Jul 10 '13 23:07

Justin k


1 Answers

I took what was in here which Mehdi Karamosly mentioned in his answer and modified it some to be a little bit simipiler and made a simple html output which you can modify to your outputs liking. You might want to add more data checking to make sure its a file/real image if you are looking to add security. I've checked it out on my computer and it works and hopefully it will work for what you need with some modification(s).

function graycolor($img){
    list($width, $height) = getimagesize($img);
    $mime = pathinfo($img, PATHINFO_EXTENSION);
    switch($mime){#use appropriate function depending on image type
        case 'jpg':
        case 'jpeg':
            $im = imagecreatefromjpeg($img);
            break;
        case 'png':
            $im = imagecreatefrompng($img);
            break;
        case 'gif':
            $im = imagecreatefromgif($img);
            break;
        default:
            #invalid type
            exit;
    }
    if(!is_color($img, $im)){#$img = string; $im = resource string
        $ret = "";
        for($i = 0; $i < $height; $i++){#loop height pixels
            for($ii = 0; $ii < $width; $ii++){#loop width pixels
                $color = imagecolorat($im, $ii, $i);
                $color = imagecolorsforindex($im, $color);
                $ret .= $color['red'] . " ";
            }
                $ret .= "\n";
        }
        return $ret;
    }else{
        #$ret = "";
        #for($i = 0; $i < $height; $i++){#loop height pixels
            #for($ii = 0; $ii < $width; $ii++){#loop width pixels
                #$color = imagecolorat($im, $ii, $i);
                #$color = imagecolorsforindex($im, $color);
                #$ret .= $color['red'] . ", " . $color['green'] . ", " . $color['blue'] . " ";
            #}
                #$ret .= "\n";
        #}
        return "color image";
    }

}
function is_color($img, $im){
    $times = 10;#number of times to check image for color
    $iscolor = false;
    list($width, $height) = getimagesize($img);
    for($i = 0 ; $i < $times && !$iscolor; $i++){
        $color = imagecolorat($im, rand(0, $width), rand(0, $height));#get random cords
        $color = imagecolorsforindex($im, $color);#get the random color's values
        if($color['red'] !== $color['green'] || $color['green'] !== $color['blue']){
            $iscolor = true;
            break;
        }
    }
    return $iscolor;
}

echo graycolor('color.jpg');#outputs color image
echo graycolor('gray.jpg');#outputs numbers
like image 77
Class Avatar answered Oct 12 '22 23:10

Class