I used to use this:
There is no leak in this code. The problem is that it loads the entire image into memory before sending it back. The memory that you observe in the w3p process is normal, and as soon as the garbage collector knocks it out, it will clear it. You should not worry about this unless you are displaying very large images.
The problem with your design is that you are using base64, which means you need to load all the content before you can decode it back into an array of bytes. Another approach would be to save the images as raw data in your database, and then use the streams to read in chunks and immediately write these fragments in response. Thus, only the currently loaded fragment is loaded into memory at a certain point in time.
Another approach that I can offer you is not to store images in the database, but to store them in the file system and save only the path to the image in the database. Then in the action of your controller all you need to do is return File(pathToTheImage, "image/jpeg") .
As an additional optimization, if these images do not change frequently, you can add the correct output caching to the controller action serving these images in order to hit it each time.
source share