16

I'm using a class library that generates a large ImageSource, > 3000x3750 pixels. I would like to convert this ImageSource to BitmapImage so that I can take advantage of DecodePixelWidth or DecodePixelHeight instead of resizing it everytime this image is generated.

I need to display this image for the user first, and most of the users have a screen resolution of 1024x768, I'm binding this ImageSource to an Image control for this, but it can be noticed how "heavy" it is.

How can I do this? Or what is the best solution for this case?

thanks!

Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72

2 Answers2

23

Try doing:

myBitmapImage = myImageSource as BitmapImage;

That works well.

StayOnTarget
  • 11,743
  • 10
  • 52
  • 81
Alexis Mathieu
  • 683
  • 5
  • 12
  • 1
    The reverse of this worked for me, converted from BitmapImage to ImageSource by casting it. Thanks! – Marwan مروان Aug 07 '13 at 00:12
  • 5
    If the cast here fails, it does so silently. so if `myImageSource` can't be casted to `BitmapImage` then `myBitmapImage ` will be `null`, I would instead use `myBitmapImage = (BitmapImage)myImageSource;` as it would at least give me a exception if all hell breaks loose. – Peter May 25 '16 at 13:59
7

The BitmapImage type inherits BitmapSource and ultimately ImageSource (both of which are abstract classes). You need to check what the actual type of your object is, i.e. check object.GetType().Name. If you're in luck, it may actually be returning a BitmapSource object and you will simply need to cast it to that type before being able to use it as such.

Noldorin
  • 144,213
  • 56
  • 264
  • 302
  • @Hans: Did you use the exact call I specified in my post? It should really return the *actual* type of the object, not the base type (or type of the variable). – Noldorin May 28 '09 at 12:20
  • @Noldorin: yes, I did, the documentation also says the return type is ImageSource... thanks –  May 28 '09 at 12:24
  • 2
    @Hans: That's quite strange indeed... the only possible reason of which I can think is that the actual type (that implements ImageSource) is private and therefore not exposed. Just to be sure: have you tried casting to any of the types derived from ImageSource. (See MSDN for a list.) Otherwise, maybe you could tell us what library you're using so we can try it for ourselves. – Noldorin May 28 '09 at 16:09