Unable to locate FromStream in Image class

2020-02-08 05:45发布

I have the following code:

Image tmpimg = null;
HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
HttpWebResponse httpWebReponse = (HttpWebResponse)httpWebRequest.GetResponse();
Stream stream = httpWebReponse.GetResponseStream();
return Image.FromStream(stream);

On the last line when I type in Image., FromStream isn't in the list. What can I do?

4条回答
再贱就再见
2楼-- · 2020-02-08 06:06

try this one:

    using System.Drawing;
    using System.IO;
    using System.Net;

    public static Image GetImageFromUrl(string url)
    {
        using (var webClient = new WebClient())
        {
            return ByteArrayToImage(webClient.DownloadData(url));
        }
    }

    public static Image ByteArrayToImage(byte[] fileBytes)
    {
        using (var stream = new MemoryStream(fileBytes))
        {
            return Image.FromStream(stream);
        }
    }
查看更多
唯我独甜
3楼-- · 2020-02-08 06:10

More detailed out example with using and the namespaces needed.

using System.Net;
using System.IO;
using System.Drawing;

public static Image GetImageFromUrl(string url)
    {
        HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);

            using (HttpWebResponse httpWebReponse = (HttpWebResponse)httpWebRequest.GetResponse())
            {
                using (Stream stream = httpWebReponse.GetResponseStream())
                {
                    return Image.FromStream(stream);
                }
            }
    }

Hopefully this saves you some time, since you can just do a quick copy and paste into your solution.

~Cheers!!

查看更多
相关推荐>>
4楼-- · 2020-02-08 06:12

You probably need using System.Drawing;.

查看更多
小情绪 Triste *
5楼-- · 2020-02-08 06:19

btw, you also need to add reference to System.Drawing.dll, only adding using System.Drawing is not enough.

查看更多
登录 后发表回答