从URL读取图像将其保存在独立存储中,并读取并绑定到图像源

时间:2012-06-20 10:20:08

标签: c# windows-phone-7 url binding isolatedstorage

我正在将图片从URL链接保存到隔离存储,之后我需要将其绑定到图像。

这是我获取并保存图像的代码:
(路径值和值是类属性)

private void saveImage(string name)
{
        path = name;

        string uri = "http://sherutnetphpapi.cloudapp.net/mini_logos/" + path;
        WebClient m_webClient = new WebClient();
        imageUri = new Uri(uri, UriKind.Relative);
        m_webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_ImageOpenReadCompleted);
        m_webClient.OpenReadAsync(imageUri);
}

void webClient_ImageOpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
        using (IsolatedStorageFile myIsf = IsolatedStorageFile.GetUserStoreForApplication())
        {
            if (myIsf.FileExists(path))
            {
                myIsf.DeleteFile(path);
            }

            IsolatedStorageFileStream fileStream = myIsf.CreateFile(path);

            StreamResourceInfo sri = null;
            sri = Application.GetResourceStream(imageUri);

            BitmapImage bitmap = new BitmapImage();
            bitmap.SetSource(sri.Stream);
            WriteableBitmap wb = new WriteableBitmap(bitmap);

            // Encode WriteableBitmap object to a JPEG stream.
            System.Windows.Media.Imaging.Extensions.SaveJpeg(wb, fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
            wb.SaveJpeg(fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
            fileStream.Close();
        }
}

在另一个课程中,我读取图像并将其绑定到图像源:

public class CompanyItem
{
    public String companyIcon { get; set; } //save the file name in the isolated storge
    public String companyName { get; set; }

    [IgnoreDataMember]
    public BitmapImage ReadImageFromStorage 
    {
        get
        {
            BitmapImage image = new BitmapImage();
            IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
            string isoFileName = this.companyIcon;
            var stream = isoStore.OpenFile(isoFileName, System.IO.FileMode.Open);
            image.SetSource(stream);
            return image;
        }
    }

xaml代码是:

<Image Height="63" HorizontalAlignment="Left" Margin="392,7,0,0" Name="imgConpamyIcon" Stretch="Fill" VerticalAlignment="Top" Width="70" CacheMode="BitmapCache" Source="{Binding ReadImageFromStorage}" />

图像位于listBox中的listBox中

请帮助我....它让我疯狂

1 个答案:

答案 0 :(得分:1)

彻底抛弃你的代码后,我得到了一些东西:

在SaveImage类中,imageUri = new Uri(uri, UriKind.Relative); 将其更改为UriKind.Absolute

然后在webClient_ImageOpenReadCompleted中,您可以直接设置bitmap.SetSource(e.Result);,而不是使用StreamResourceInfo

而且,我再次知道将XagL中的Image标签的Source属性绑定到BitmapImage是否有效(它在后面的代码中有效)