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

时间:2019-10-14 21:00:23

标签: c# image-processing base64url

我遇到问题,我想将图像从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);
    }

2 个答案:

答案 0 :(得分:0)

这是执行中出现的错误: Error Msg

答案 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块中看到的异常,调试这些类型的错误要容易得多,因此您可以弄清楚什么是错误。