Page 1 of 1

RGB data from Jpg in an array

Posted: Tue Nov 17, 2009 7:21 pm
by gth759k
Does anyone know a way to get the raw RGB data from a jpg image and store it in an array or temporary file?
Any help would be appreciated. Thanks.

Re: RGB data from Jpg in an array

Posted: Tue Nov 17, 2009 8:36 pm
by Weiry
The only foreseeable way i can think of doing this, would be to first convert the jpg image into a bmp format in which you can then directly access the HEX colour values. This is because jpg uses a compression format that im not sure how to decode. You could try search for a php jpg decoder. However if you were to convert your JPG's to a BMP first you could do the following.

You need to determine the size of the header in HEX, then store that separately to the RGB data.
The first HEX value after the end of the header is the start of your RGB data.
For each pixel, the RGB value of that pixel is contained in every 3 HEX values.
eg. FF FF FF = white
eg. FF 00 00 = red

So you would need to convert the data into an array, splitting the data by every 3 values. Keep in mind though, BMP data starts from the bottom right, and reads right to left, bottom to top.

I wrote a small image create script for a challenge a while ago. It might give you an understanding how to achieve something like what your after.

ImageCreate

Re: RGB data from Jpg in an array

Posted: Tue Nov 17, 2009 10:16 pm
by Weiry
from what i read, doesn't imagecolorat() only return an int array for a specified pixel?

For that you would need to know the width/height of the image. Then perform hex conversion to obtain the raw data?

Well i suppose it really depends on exactly what the OP wants to do with only rgb data without the header info.

Re: RGB data from Jpg in an array

Posted: Wed Nov 18, 2009 12:07 am
by gth759k
Thanks. imagecolorat() was able to accomplish what I wanted. Here's the script I came up with:

Code: Select all

 
    $photo = "tiger.jpg";
    $image = imagecreatefromjpeg($photo);
    list($width, $height, $type, $attr) = getimagesize($photo);
    
    for ($x = 0; $x <= $width-1; $x++) {
        for ($y = 0; $y <= $height-1; $y++) {
            $rgb = imagecolorat($image, $x, $y);
            $r = ($rgb >> 16) & 0xFF;
            $g = ($rgb >> 8) & 0xFF;
            $b = $rgb & 0xFF;
            
            $row = $r.','.$g.','.$b;
            $data[] = $row;
        }
    }
    
    $name = explode('.', $photo);
    $file = $name[0].'.csv';
    $handle = fopen($file, "w");    
    
    foreach ($data as $line) {
        fputcsv($handle, split(',', $line));
    }
 
    fclose($handle);
 
It traverses each pixel of the photo and stores the rgb data in a csv file of the same name as the photo.