在我的XAML中,我有:
<Image Height="150" HorizontalAlignment="Left" Margin="0,4,0,0" Name="imgLogo" Stretch="Fill" VerticalAlignment="Top" Width="417" />
<Image Height="343" HorizontalAlignment="Left" Margin="0,155,0,0" Name="imgPhoto" Stretch="Fill" VerticalAlignment="Top" Width="417" />
在后面的C#代码中,我有:
WebClient wcForLogo = new WebClient();
wcForLogo.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wcForLogo_DownloadStringCompleted);
wcForLogo.DownloadStringAsync(new Uri("http://mySite/logo.gif"));
WebClient wcForPhoto = new WebClient();
wcForPhoto.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wcForPhoto_DownloadStringCompleted);
wcForPhoto.DownloadStringAsync(new Uri("http://mySite/photo.jpg"));
但是现在我不知道如何捕获图像并将其发布到我构建的XAML控件中。
2个问题:
答案 0 :(得分:2)
如果您只想显示图片,则无需使用WebClient。您可以直接在图像源中设置Uri,控件将负责下载:
imgLogo.Source = new BitmapImage(new Uri("images/yourPicture.png", UriKind.Relative));
请注意,Image控件不支持GIF。您仍然可以使用ImageTools库中的转换器显示它们:Display GIF in a WP7 application with Silverlight
答案 1 :(得分:1)
using System.Net;
using System.IO;
private void Form1_Load(object sender, EventArgs e)
{
WebClient webclient = new WebClient();
webclient.DownloadDataAsync(new Uri("http://mySite/logo.gif"));
webclient.DownloadDataCompleted += callback;
}
void callback(object sender,DownloadDataCompletedEventArgs e)
{
var ms = new MemoryStream(e.Result);
pictureBox1.Image = Image.FromStream(ms);
}
答案 2 :(得分:0)
如果你想保存在这样的隔离存储中
WebClient m_webClient = new WebClient();
Uri m_uri = new Uri("http://URL");
m_webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
m_webClient.OpenReadAsync(m_uri);
}
void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
int count;
Stream stream = e.Result;
byte[] buffer = new byte[1024];
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
using (System.IO.IsolatedStorage.IsolatedStorageFileStream isfs = new IsolatedStorageFileStream("IMAGES.jpg", FileMode.Create, isf))
{
count = 0;
while (0 < (count = stream.Read(buffer, 0, buffer.Length)))
{
isfs.Write(buffer, 0, count);
}
stream.Close();
isfs.Close();
}
}
获取isosore的图像形式:
byte [] data;
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream isfs = isf.OpenFile(uri, FileMode.Open, FileAccess.Read))
{
data = new byte[isfs.Length];
isfs.Read(data, 0, data.Length);
isfs.Close();
}
}
MemoryStream ms = new MemoryStream(data);
BitmapImage bi = new BitmapImage();
bi.SetSource(ms);
If you give the image name as image then set the source as bi:
image.source = bi;
如果您想直接添加
WebClient client = new WebClient();
Stream stream = client.OpenRead(imageUrl);
Bitmap bitmap = new Bitmap(stream);
image.source = bitmap;
答案 3 :(得分:0)
假设您的图片控件名为MyImage
,您可以这样做以从网址加载图片:
MyImage.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri("http://mySite/photo.jpg"));
无需为了下载图像而完成所有管道工作,框架已经为您完成了这项工作!