[英]Convert Image to Base64 String from URL download
我有問題,我想將圖像從 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);
}
您似乎正在使用來自沒有響應的服務器的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.
您可以通過忽略從服務器返回的內容長度來解決此問題,並將所有數據讀入 memory 直到響應完成:
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
塊中看到的異常,則調試這些類型的錯誤會容易得多,因此您對錯誤是什么有所了解。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.