简体   繁体   中英

BitmapImage sourceStream is null in WPF

I'm using the following function to load a bitmap image

private BitmapImage fileNameBitMap(string filePath)
{
    if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath))
    {
        try
        {
            BitmapImage bitmap = new BitmapImage();
            bitmap.BeginInit();
            bitmap.CacheOption = BitmapCacheOption.OnLoad;


            bitmap.DecodePixelWidth = 200;
            bitmap.UriSource = new Uri(filePath);
            bitmap.CreateOptions = BitmapCreateOptions.IgnoreColorProfile;

            bitmap.EndInit();
            image = bitmap;
            return bitmap;
        }
        catch
        {
            return null;
        }
    }
    return null;
}

When I debug the bitmap.SourceStream I find it equal to null, also I find a FormatNotSupportedException is thrown. I need to store the BitmapImage in a stream in a process of converting it to a byte[].

您应该简单地将图像文件的内容读入byte[]

var bytes = File.ReadAllBytes(filePath);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM