zoukankan      html  css  js  c++  java
  • BitmapImage处理网络图片,例如阿里云获取的图片。异步加载到需要显示的控件上。提升速度非常明显。

    想直接把网络图片赋给控件,又要下载又要缓存,速度非常慢。不流畅。

    需要进行处理,异步加载会显著提升速度。方法如下:

            public static BitmapImage ByteArrayToBitmapImage(byte[] byteArray)
            {
                BitmapImage bmp = null;
                try
                {
                    bmp = new BitmapImage();
                    bmp.BeginInit();
                    bmp.StreamSource = new MemoryStream(byteArray);
                    bmp.EndInit();
                }
                catch
                {
                    bmp = null;
                }
                return bmp;
            }

    调用以上方法显示在控件中:

                    
               //注:1
                string tttt = 获取的网络图片地址; Task t = new Task(() => { WebClient wc = new WebClient(); wc.Credentials = CredentialCache.DefaultCredentials; ///方法一: Byte[] pageData = wc.DownloadData(tttt); instance.Dispatcher.BeginInvoke(((Action)(() => { instance.imageBrush.ImageSource = ByteArrayToBitmapImage(pageData); } ))); }); t.Start();

    注1:“System.InvalidOperationException”类型的异常在 WindowsBase.dll 中发生,但未在用户代码中进行处理
    其他信息: 调用线程无法访问此对象,因为另一个线程拥有该对象。如果不定义一个string 类型的变量 转换 会报以上的错误。堆栈怎么就找不到了,定义一个就找到了。说这个意思。

    图片经过这样处理就是控件先加载出来,图片慢慢加载出来,速度非常流畅。直接赋给控件图片和控件一起缓存非常迟钝。

  • 相关阅读:
    LeetCode "Super Ugly Number" !
    LeetCode "Count of Smaller Number After Self"
    LeetCode "Binary Tree Vertical Order"
    LeetCode "Sparse Matrix Multiplication"
    LeetCode "Minimum Height Tree" !!
    HackerRank "The Indian Job"
    HackerRank "Poisonous Plants"
    HackerRank "Kundu and Tree" !!
    LeetCode "Best Time to Buy and Sell Stock with Cooldown" !
    HackerRank "AND xor OR"
  • 原文地址:https://www.cnblogs.com/Early-Bird/p/5526438.html
Copyright © 2011-2022 走看看