Folks, I didn't get a chance to finish this review. I've got some notes here, and I have a proposed (100% untested) branch at https://github.com/andrewnicols/moodle/commit/MDL-45910-master
Hi Nejc,
Thank you for working on this issue. I realise that i's quite a complex one and has been sitting for some time without much love. We appreciate your time and effort in looking into it.
On the whole the patch looks okay, but I can see that there are some cases which may be missed and will cause errors to be thrown. I also feel that there is a lot of duplication in this function which could easily be removed with a minor refactor and introduction of a new protected or private function to perform the rotation (e.g. {{rotate_image_by_angle}} taking {{string $source, int $angle, int $width, int $height}} and returning an array containing the final width, height, and image data).