Convert simple PHP script in Grav Twig

I’m trying to transfer my current website to Grav.
I’m using to resize images, and I’d like continuing using it, instead of the builtin Grav method.

However, I’m having a hard time implementing it into Grav.

I’ve tried several things including preg_replace and also the plugin way but I’m not able to do it.

Do you have any suggestions, how I can convert my simple PHP in Twig and make it work?

// Image
function getImage($img, $alt) {
    echo '<img class="lazyload" src="" data-src="'.$img.'" data-srcset="'.$img.'?w=550 500w,'.$img.'?w=750 700w,'.$img.'?w=900w 1024w" alt="'.$alt.'">';