Skip to content

Instantly share code, notes, and snippets.

@malkitsingh
Created July 23, 2015 06:32
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save malkitsingh/a3629a71ed6c50fcde6c to your computer and use it in GitHub Desktop.
Save malkitsingh/a3629a71ed6c50fcde6c to your computer and use it in GitHub Desktop.
public String ConvertImageURLToBase64(String url)
{
StringBuilder _sb = new StringBuilder();
Byte[] _byte = this.GetImage(url);
_sb.Append(Convert.ToBase64String(_byte, 0, _byte.Length));
return _sb.ToString();
}
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);
}
@talhakaanozkan
Copy link

{"'System.Net.FileWebRequest' türündeki nesne 'System.Net.HttpWebRequest' türüne atılamadı."}
not working.

@malkitsingh
Copy link
Author

hi @talhakaanozkan
This code was written long back, make sure you are importing all the required dependencies.

@rahulbagal
Copy link

rahulbagal commented Sep 24, 2020

Thanks. Its a quick helpful reference. working fiddle - https://dotnetfiddle.net/D22EBb

@nipun525
Copy link

Great.
This was very useful.

Thanks

@arjitg
Copy link

arjitg commented Apr 2, 2023

@rahulbagal there is an error in the fiddle you shared,

Run-time exception (line 22): Object reference not set to an instance of an object.

This is coming from Convert.ToBase64String method. Any idea how to fix it?

Update: It is because of the image link shown there doesn't exist anymore so the data is blank. Code works. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment