To generate the thumbnails, here's an example https://stackoverflow.com/a/8631924/1766544
To serve them, that's a pretty open-ended question. However you do it, I'd recommend generating the small image only if it's requested, but then make sure you keep it around so you can provide it on demand, without having to generate it again.