WPF BitmapSource ImageSource

前端 未结 3 1857
有刺的猬
有刺的猬 2021-01-12 14:24

I am binding an Image.Source property to the result of the property shown below.

public BitmapSource MyImageSource
{
    get
    {
        BitmapSource sour         


        
相关标签:
3条回答
  • 2021-01-12 14:44

    The problem was the BitmapCacheOption option, changing to BitmapCacheOption.OnLoad works.

    With BitmapCacheOption.None the BitmapSource isn’t decoded until the image is rendered, but the stream with the png in it is already disposed at that point. If you cache OnLoad, it’ll decode right away and cache the results, rather than trying to decode later when the stream no longer exists.

    0 讨论(0)
  • Also, have you tried just using a BitmapImage to load the image? It works fine with PNG, BMP, and JPEG.

    It's also a specialized type of BitmapSource, so you could just replace your code in your property with this:

    BitmapImage img = new BitmapImage(new Uri(@"C:\Temp\logo.png"));
    return img;
    
    0 讨论(0)
  • 2021-01-12 14:49

    Are you positive it's a PNG and not just a renamed Bitmap or Jpeg? If you create a new Bitmap image and then just rename it and change the file extension, this error is reproducible.

    If I use a known PNG with your code, I don't get your issue, but a COM exception is thrown:

    The handle is invalid. (Exception from HRESULT: 0x80070006 (E_HANDLE))

    Can you try it out with a random PNG off the web and see if you get the same result?

    0 讨论(0)
提交回复
热议问题