Optimized algorithm: use custom function to convert color index to rdb and vice versa, reduce loops and array_merge. Added validation for update image pixel.