Sunday, August 7, 2016

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 !!!

No comments :

Post a Comment