将图像转换为 Base64 字符串来自 URL 下载

Convert Image to Base64 String from URL download

我有问题,我想将图像从 url 转换为 base64,但出现错误

这是url:https://www.jotform.com/widget-uploads/imagePreview/92613577901663/2922362Principios%20-%20Resultados.png

    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.

您可以通过忽略从服务器返回的内容长度来解决此问题,并将所有数据读入内存直到响应完成:

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 块中看到的异常,则调试此类错误会容易得多,因此您对错误是什么有所了解。