我遇到问题,我想将图像从url转换为base64,但是出现错误
public String ConvertImageURLToBase64(String url)
{
StringBuilder sb = new StringBuilder();
Byte[] vbyte = this.GetImage(url);
sb.Append(Convert.ToBase64String(vbyte, 0, vbyte.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);
}
答案 0 :(得分:0)
答案 1 :(得分:0)
您似乎正在使用Content-Length
来自没有响应的服务器的响应,因此,您使用的是默认值-1创建数组。由于以下异常而失败:
Exception thrown: 'System.ArgumentOutOfRangeException' in mscorlib.dll An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll Non-negative number required.
您可以通过忽略服务器返回的内容长度,然后将所有数据读入内存直到完成响应来解决此问题:
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 (MemoryStream ms = new MemoryStream())
{
stream.CopyTo(ms);
buf = ms.ToArray();
}
stream.Close();
response.Close();
}
catch (Exception exp)
{
buf = null;
}
return (buf);
}
供以后参考:如果显示在try
/ catch
块中看到的异常,调试这些类型的错误要容易得多,因此您可以弄清楚什么是错误。