1

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

这是网址: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);
    }
4

2 回答 2

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

于 2019-10-14T21:59:13.247 回答
0

这是执行中出现的错误: 错误信息

于 2019-10-14T21:18:27.803 回答