我尝试从网站下载图片并根据该图片创建位图。它看起来像这样:
public void test()
{
PostWebClient client = new PostWebClient(callback);
cookieContainer = new CookieContainer();
client.cookies = cookieContainer;
client.download(new Uri("SITE"));
}
public void callback(bool error, string res)
{
byte[] byteArray = UnicodeEncoding.UTF8.GetBytes(res);
MemoryStream stream = new MemoryStream( byteArray );
var tmp = new BitmapImage();
tmp.SetSource(stream);
}
我收到"未指定的错误"在回调方法的最后一行。有趣的事实是,如果我使用BitmapImage(新的Uri(" SITE"))它运作良好......(我不能这样做,因为我想从该URL抓取cookie。图像是一个jpg。 PostWebClient类 - > http://paste.org/53413
答案 0 :(得分:21)
这是Bitmap类文档中最简单的代码。
System.Net.WebRequest request =
System.Net.WebRequest.Create(
"http://www.microsoft.com//h/en-us/r/ms_masthead_ltr.gif");
System.Net.WebResponse response = request.GetResponse();
System.IO.Stream responseStream =
response.GetResponseStream();
Bitmap bitmap2 = new Bitmap(responseStream);
答案 1 :(得分:7)
最简单的方法是通过WebClient实例打开网络流,并将其传递给the constructor类的Bitmap:
using (WebClient wc = new WebClient())
{
using (Stream s = wc.OpenRead("http://hell.com/leaders/cthulhu.jpg"))
{
using (Bitmap bmp = new Bitmap(s))
{
bmp.Save("C:\\temp\\octopus.jpg");
}
}
}
答案 2 :(得分:3)
您可以尝试以下代码:
private Bitmap LoadPicture(string url)
{
HttpWebRequest wreq;
HttpWebResponse wresp;
Stream mystream;
Bitmap bmp;
bmp = null;
mystream = null;
wresp = null;
try
{
wreq = (HttpWebRequest)WebRequest.Create(url);
wreq.AllowWriteStreamBuffering = true;
wresp = (HttpWebResponse)wreq.GetResponse();
if ((mystream = wresp.GetResponseStream()) != null)
bmp = new Bitmap(mystream);
}
finally
{
if (mystream != null)
mystream.Close();
if (wresp != null)
wresp.Close();
}
return (bmp);
}
答案 3 :(得分:1)
试试这个:
string url ="http://www.google.ru/images/srpr/logo11w.png"
PictureBox picbox = new PictureBox();
picbox.Load(url);
Bitmap bitmapRemote = (Bitmap) picbox.Image;
url - 网络图片,我们创建新的实例对象PictureBox,然后调用 NOT ASYNC 过程从url加载图片,当检索到的图像将图像作为位图时。 您还可以使用线程处理表单,在其他线程中调用load,并在完成后通过deleate方法检索图像。