As a developer you need to show a user an image, but you don’t want the image cached or exposed to anonymous visitors and for it to be protected while at rest.
The Solution: It is up to you, as the developer, to keep the image safely stored while at rest. One method we will visit today is retrieving the image as first a System.Drawing.Image object, then converting that to an array of bytes and then converting that to a Base 64 encoded string. Sounds complicated, but it isn’t and it’s safe and it’s fast.
Step 1 – Part A: Create a webservice that will execute the task. The first part is easy, once you have access to the file create a reference to it using the .NET framework Drawing class – in this example we use the System.Drawing.Image.
Step 1 – Part B: Next turn that object into an array of bytes. You can do so once again by using the .NET framework class MemoryStream and invoke a Using call to save the Drawing.Image object to the MemoryStream in its “RawFormat” (which is an attribute of the Drawing object). You can then create an object as an array of Bytes and assign the stream (as an array) to this new array of Bytes and then return that back to the process.
Step 1 – Part C: Next take this array of Bytes and convert it to a Base64 String, that becomes a generic string and can be properly assigned to a generic image control as long as it has the header “data:Image/Jpeg;base64,{0}”
The next problem: This is all well and good, the file is stored protected and is protected in transit, but is very large (as measures in bytes) when converted ultimately to a base 64 encoded string. So, if we try to execute this process at runtime and cache it (as maybe the case when viewstate exists) we end up with a very bloated process that can very well slow down load times even for just a couple of images.
The solution: Create an asynchronous web service that can be invoked client side (via a script) on demand when a user initiates an action, such as mousing over an object to actually see the image. Because the process runs as a client-side background process it is very efficient and has no affect otherwise on the page. Also since it is client side, nothing is stored or cached, so when the page is recycled so is the image.
Invoking the web service client side: How we did this is our example was to ultimately invoke an ajax call when a user initiated a mouseover event which called the webservice via a client-side script to pull down the base64 string (we had to serialize it) and then build the proper HTML markup to ultimately display the image
Sounds complicated, but when you break it down, it really isn’t. You end up with an elegant, fast and safe way to show protected images (as might be the case for sensitive crime scene photos or other legal documents.)