If you still want to store the images in the database, then you'll have to modify your script structure.
You can't simply include the image data in-line with the HTML. (Okay, you can if you base64 encode it and use a special version of the IMG tag, but this is rarely used).
Instead, you need to do something like:
<img src="image.php?id=123">
and then have an image.php script that does something like what you have above; query the DB, get the image data, output the appropriate Content-Type header using [man]header/man, and then echo out the image data.