Covert Image URL in to base64 string

Suppose you have your images hosted in azure blob storage. And you access the images using the URL. Else you have some images from another online location where you have only the URL.

I got a requirement recently on a project to generate a Vcard. For that I need the base64 string of the image, as all the data will be saved in to a text file. So I used the following code to first download the image them convert it to base64 string.

    public String GetImageData(String url)  
     {  
       StringBuilder _sb = new StringBuilder();  
       Byte[] _byte = GetImage(url);  
       //convert byte array in to base 64 string  
       _sb.Append(Convert.ToBase64String(_byte, 0, _byte.Length));  
       return _sb.ToString();  
     }  
     // Download image in to byte array  
     private byte[] GetImage(string url)  
     {  
       Stream stream = null;  
       byte[] buf;  
       try  
       {  
         WebProxy myProxy = new WebProxy();  
         HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);  
         HttpWebResponse response = (HttpWebResponse)req.GetResponse();  
         stream = response.GetResponseStream();  
         using (BinaryReader br = new BinaryReader(stream))  
         {  
           int len = (int)(response.ContentLength);  
           buf = br.ReadBytes(len);  
           br.Close();  
         }  
         stream.Close();  
         response.Close();  
       }  
       catch (Exception exp)  
       {  
         buf = null;  
       }  
       return (buf);  
     }  
     private int? GetCardId(string slug)  
     {  
       string[] slugElements = slug.Split('_');  
       try  
       {  
         return Convert.ToInt32(slugElements.Last());  
       }  
       catch (Exception ex)  
       {  
         return null;  
       }  
     }  

Hope this helps.

Happy Coding !!!

Comments

  1. Thanks For Sharing The Information The Information Shared Is Very Valuable Please Keep Updating Us
    by Read hosting review website providing many hosting reviews about ipage, wp engine, siteground hosting review etc.

    ReplyDelete
  2. I can easily follow the steps, it's good that you showed how to do it. Great job. Well done posting this, keep posting more content like this. Thanks for sharing.
    Local Citations

    ReplyDelete

Post a Comment

Popular posts from this blog

Responsive Web Design

Affine Cipher in C#

Contract First Development in WCF 4.5