Thumbnails limit max first 6 images
If I understand you correctly then you just need to break out of the foreach loop after you got 6 thumbnails saved in the $output variable. With that addition the end of your loop would look like this:

if ($i == 1) break;
$i--;
endforeach;