PHP change colors image optimization

69 views Asked by At

I wrote this rough code that not only changes a color of a certain color in a PHP image but orders the pixels while doing it, so if I'd like to replace it with an actual image I can. This code processes a rectangle that is rotated to the left by reading from top right->left. This is what I have so far. Everything works... However it is REALLY slow. I was wondering if there could be another approach to this to make it faster. Thanks.

<?php    
       while (count($yArr) > 0) {
            $startY = min($yArr);
            $arrSmall = array_keys($yArr, $startY);
            $theX = 0;
            for ($i = 0; $i < count($arrSmall); $i++) {
                $x = $xArr[$arrSmall[$i]];
                if ($x > $theX) {
                    $theX = $x;
                }
            }
            $startingX = $theX;
            while ($startingX >= $minX) {
                $minY = 10000;
                $arr = array_keys($xArr, $startingX);
                if (count($arr) != 0) {
                    $uSKey = -1;
                    for ($i = 0; $i < count($arr); $i++) {
                        $y = $yArr[$arr[$i]];
                        if ($y < $minY) {
                            $minY = $y;
                            $uSKey = $arr[$i];
                        }
                    }
                    if ($uSKey != -1) {
                        unset($xArr[$uSKey]);
                        unset($yArr[$uSKey]);
                        $xArr = array_values($xArr);
                        $yArr = array_values($yArr);
                    }
                    imagesetpixel($origImage, $startingX, $minY, $newColor);
                }
                $startingX--;
            }
        }
?>
1

There are 1 answers

1
ChristianM On

Use higher level methods that GD offers you to do the operations you want to do:

http://php.net/manual/en/function.imagerotate.php

http://php.net/manual/en/function.imagecolorexact.php http://php.net/manual/en/function.imagecolorset.php

could probably help you reach your goal with acceptable speed.