Question

I have a string containing bitmap data. Basically, it holds cycles of 1 byte of red, green, blue for each pixel in an image.

I want to manipulate the 8-bit integer value of each color channel in the bitmap. Currently I do this using unpack('C'.strlen($string)) which gives me an array of integers. This is very slow as it converts a lot of data.

Is there a more efficient way to access and modify data from a string as integers?

By more efficient, I mean more efficient than this:

for($i = 0, $l = strlen($string); $i < $l; $i++)
    $string[$i] = chr(floor(ord($string[$i]) / 2));

The manipulation where I divide by 2 is simply an example. The manipulations would be more advanced in a real example.

The problem with the above example is that for say 1 million pixels, you get 3 million function calls initialized from PHP (chr, floor, ord). On my server, this amounts to about 1.4 seconds for an example picture.

No correct solution

OTHER TIPS

PHP strings essentially are byte arrays. The fastest way would simply be:

for ($i = 0, $length = strlen($data); $i < $length; $i++) {
    $byte = $data[$i];

    ...
}

If you manipulate the byte with bitwise operators, you'll hardly get more efficient than that. You can write the byte back into the string with $data[$i] = $newValue. If you need to turn a single byte into an int, use ord(), the other way around use chr().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top