Skip to main content

Peter Marshall

Using Base64EncodedStrings for images

3 min read

The images are in a legacy system ( aspx pages). Some are generated dynamicly by that system (bar codes). The new system, mobile freindly, angualar, asp,net mvc requires to print docuements with these images in. So I get the content for the documents to be printed, and find it has img tags in it and these point to the relative path in the aspx application. 

I extract the relative path from the image tags, nice regex here. 

string imgTagSelectionPattern = @"<img.*?src=""(?<url>.*?)"".*?>";

Get the image and convert it to a base64encoded string

private string GetImageContentAsBase64EncodedString(Uri url)
    var content = string.Empty;
        var request = (HttpWebRequest)WebRequest.Create(url);
        using (var response = (HttpWebResponse)request.GetResponse())
            if (response.StatusCode == HttpStatusCode.OK)
                var receiveStream = response.GetResponseStream();
                if (receiveStream != null)
     byte[] outData;
     var tempMemStream = new MemoryStream();
     outData = tempMemStream.ToArray();
     content = Convert.ToBase64String(outData);
}                  content = Convert.ToBase64String(outData);                 }             }         }     }     catch     {         //this is the base64 encoding of an 'image not found' image         content = "iVBORw0KGgoAAAANSUhEUgAAAJYAAAAaCAIAAADaETIWAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAG+SURBVGhD7ZbrdYMwDIUzFwMxD9OwTIZJLT+kK4NSTsGhavX9smW9b06SxytwTkjonpDQPSGhe/65hM9lehDT8qyWq1nngckzpyRM7T3mtV5+MSTUbp8fGCAkvIR3Eg7eryMJ05ZSp2TIJGv7jsIJ2IbSc1ChPOx6VooiHIYbgrBtItu11diGV6P0IJIU+14bkmZaFk8Spo7V1uRSZ1jnNowythMZazZIDMdGyS/x7T3bmy9eILNGiiescB2t+7XaaFnJDCWGcKWEPKe6gJPAHujK2+EDoZJltIWde0fJsk1RwUJmuFHuYBtYYgwflZDsQjHKiOJIJwUnyxi7g0IZcdMBgBR/E26UO9gGlhjDByXE2dR+mPb6zdjG7rQZs/QvDBYyw41yB9vAEmO4R0I6spE9BXDd4d1O+YEubXd4VkhswgyXbrILlttrg9zB5W/9FtIxk/+o9UaCpy3DV7odWLsrlwYGtWz9MlVswggXe/4HWp/sNqT5eU3nvurFnJLwPDQsTNivNDjAzRLSx1s+yZ2gwSFulhC/dBKh3w+4XcLgLCGhe0JC94SE7gkJ3RMSuickdE9I6J6Q0Dmv1xcjhYT1jnd5CwAAAABJRU5ErkJggg==";     }     return content; }

Then prepend it with the following "data:image/png;base64," replace the original src string with the new string and deliver all that client side in the new application.