wpf 一个改版了一下的方法,释放图片资源,图片不存在就变成自己的默认图片,而不是报错

例如,我要绑定一个员工的图片信息
//员工信息
private void Select_StaffMassage() {

        string SImg = Convert.ToString(Application.Current.Properties["SImg"]);
        IDStaffImg.ImageSource = _10Base.BindingImg.GetImage(System_Path + "_08Server_Img//Simages//" + SImg);
    }

class BindingImg
{
//释放资源
public static BitmapImage GetImage(string imagePath)
{
BitmapImage bitmap = new BitmapImage();

        if (File.Exists(imagePath))
        {
            bitmap.BeginInit();
            bitmap.CacheOption = BitmapCacheOption.OnLoad;

            using (Stream ms = new MemoryStream(File.ReadAllBytes(imagePath)))
            {
                bitmap.StreamSource = ms;
                bitmap.EndInit();
                bitmap.Freeze();
            }
        }
        else
        {
            bitmap.BeginInit();
            bitmap.CacheOption = BitmapCacheOption.OnLoad;
            string System_ = System.AppDomain.CurrentDomain.BaseDirectory + "_08Server_Img//Simages//V_02.png";
            using (Stream ms = new MemoryStream(File.ReadAllBytes(System_)))
            {
                bitmap.StreamSource = ms;
                bitmap.EndInit();
                bitmap.Freeze();
            }
        }

        return bitmap;
    }
}

我们需要提前准备一张图片放在程序中,当找不到员工图片时,有一张图片替换,而不是报错,放在bin目录下

发布了115 篇原创文章 · 获赞 36 · 访问量 9886

猜你喜欢

转载自blog.csdn.net/weixin_44548307/article/details/103122979