1

Uri から BitmapImage へのコンバーターに問題があります。Uri は Web 上の画像の URL です。リストボックスのアイテムでこのコンバーターを使用します。

Web ページから画像をダウンロードし、このストリームから作成します BitampImage

問題は、リストボックスが約 100 ~ 250 の項目で構成されている場合、アプリがフリーズすることです。別のスレッドで WebRequestMethod を呼び出してみましたが、機能しません。

コードのルート部分は次のとおりです。

private static BitmapImage GetImgFromAzet(int sex, Uri imgUri)
{
    try
    {
        if (imgUri == null)
        {
            if (sex == (int)Sex.Man)
            {
                return new BitmapImage(new Uri(@"pack://application:,,,/Spirit;Component/images/DefaultAvatars/man.jpg",
                        UriKind.RelativeOrAbsolute));
            }
            else
            {
                return new BitmapImage(new Uri(@"pack://application:,,,/Spirit;Component/images/DefaultAvatars/woman.jpg",
                        UriKind.RelativeOrAbsolute));
            }
        }
        else
        {
            BitmapImage image = null;

            Task.Factory.StartNew(() =>
              {
                  WebRequest webRequest = WebRequest.CreateDefault(imgUri);
                  webRequest.ContentType = "image/jpeg";
                  WebResponse webResponse = webRequest.GetResponse();

                  image = new BitmapImage();
                  image.CreateOptions = BitmapCreateOptions.None;
                  image.CacheOption = BitmapCacheOption.OnLoad;
                  image.BeginInit();
                  image.StreamSource = webResponse.GetResponseStream();
                  image.EndInit();
                  return image;

                  //((System.Action)(() =>
                  //{


                  //    //webResponse.Close();

                  //})).OnUIThread();

              });

            return image;
        }
    }
    catch (Exception)
    {

//デフォルトは new BitmapImage(new Uri(PokecUrl.Avatar,UriKind.RelativeOrAbsolute)); を返します。} }

私の目的は、Web から画像をダウンロードし、彼から BitamImage オブジェクトを作成し、Image コントロールのソースとして返すことですが、アプリのフリーズを避ける必要があります。また問題は、webResponse を閉じると、すべてのコードが壊れてしまうことです。

編集:

私はこれを試します:

BitmapImage image;
WebRequest req = WebRequest.CreateDefault(imgUri);
req.ContentType = "image/jpeg";

using (var res = req.GetResponse())
{
        image = new BitmapImage();
        image.CreateOptions = BitmapCreateOptions.None;
        image.CacheOption = BitmapCacheOption.OnLoad;
        image.BeginInit();
        image.UriSource = imgUri;
        image.StreamSource = res.GetResponseStream();
        image.EndInit();
}

しかし、どこかにバグがあるはずです。コードが壊れています。

何かアドバイス?

4

1 に答える 1

3

バインディング コンバーターは常に UI スレッドで実行されます。そのため、Convert メソッドで他のスレッドを開始できますが、最終的には (このスレッドからのフィードバックが必要なため) 完了するまで待たなければならないため、アプリがブロックされます。

この問題を解決するには、たとえばBinding.IsAsync プロパティを使用できます。

public class ListItemViewData
{
   private readonly Uri _uri;
   private readonly Sex _sex; 

   ListItemViewData(Uri uri, Sex sex)
   {
      this._uri = uri;
      this._sex = sex;
   }

   public BitmapSource Image
   {
       get
       {
           // Do synchronous WebRequest 
       }
   }
}

xaml での使用法 (リストボックス項目の DataTemplate 内):

<Image Source="{Binding Path=Image, IsAsync=True}"/>

編集済み

私は BitmapImage クラスに飛び込み、非同期で動作する Uri パラメーターを持つかなりの ctor を持っていることを発見しました。

したがって、自分で WebRequest を実行しないでください。このようにしてください:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    var uri = (Uri)value;
    return new BitmapImage(uri) { CacheOption = BitmapCacheOption.None };
} 

編集済み 2

ビュー データ クラス。

public class ListItemViewData : INotifyPropertyChanged
{
    public ListItemViewData(Uri uri)
    {
        this._uri = uri;
    }

private readonly Uri _uri;
public Uri Uri
{
    get 
    {
        return this._uri; 
    }
}

private BitmapSource _source = null;
public BitmapSource Image
{
    get
    {
        return this._source;
    }
    set 
    {
        this._source = value;
        this.OnPropertyChanged("Image");
    }
}

public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string p)
{
    var pc = this.PropertyChanged;
    if (pc!=null)
    { 
        pc(this, new PropertyChangedEventArgs(p));
    }
}
}

画像のダウンロードを実行するヘルパー:

public static class WebHelper
{
    public static Stream DownloadImage(Uri uri, string savePath)
    {
        var request = WebRequest.Create(uri);
        var response = request.GetResponse();
        using (var stream = response.GetResponseStream())
        {
            Byte[] buffer = new Byte[response.ContentLength];
            int offset = 0, actuallyRead = 0;
            do
            {
                actuallyRead = stream.Read(buffer, offset, buffer.Length - offset);
                offset += actuallyRead;
            }
            while (actuallyRead > 0);
            File.WriteAllBytes(savePath, buffer);
            return new MemoryStream(buffer);
        }
    }   
}

モデルを埋めるときは、ファイルをダウンロードして画像ソースを設定する別のスレッドを開始する必要があります。

this._listItems.Add(new ListItemViewData(new Uri(@"http://lifeboat.com/images/blue.ocean.jpg")));
//...
var sc = SynchronizationContext.Current;
new Thread(() =>
{
    foreach (var item in this._listItems)
    { 
        var path = "c:\\folder\\"+item.Uri.Segments.Last();
        var stream = WebHelper.DownloadImage(item.Uri, path);

        sc.Send(p =>
            {
                BitmapImage bi = new BitmapImage();
                bi.BeginInit();
                bi.StreamSource = (Stream)p;
                bi.EndInit();
                item.Image = bi;
            }, stream);
    }
}).Start();
于 2011-02-10T08:21:26.617 に答える