Search code examples
wpfsharpdxhelix-3d-toolkit

With HelixToolkit.SharpDX.Wpf how do I set the DiffuseMap on a PhongMaterial from an ImageSource?


The DiffuseMap property of a PhongMaterial accepts a Stream.

If I have an ImageSource, how do I convert it to something acceptable to the property? Note that I need to be able to do this fast, in memory.

In the examples in the source code I can only find examples of loading images from file:

var image = LoadFileToMemory(new System.Uri(@"test.png", System.UriKind.RelativeOrAbsolute).ToString());
this.ModelMaterial = new PhongMaterial
        {
            AmbientColor = Colors.Gray.ToColor4(),
            DiffuseColor = Colors.White.ToColor4(),
            SpecularColor = Colors.White.ToColor4(),
            SpecularShininess = 100f,
            DiffuseAlphaMap = image,
            DiffuseMap = LoadFileToMemory(new System.Uri(@"TextureCheckerboard2.dds", System.UriKind.RelativeOrAbsolute).ToString()),
            NormalMap = LoadFileToMemory(new System.Uri(@"TextureCheckerboard2_dot3.dds", System.UriKind.RelativeOrAbsolute).ToString()),
        };

LoadFileToMemory simply takes the bytes from a file and returns it as a MemoryStream.


Solution

  • By ImageSource you mean a BitmapSource or DrawingImage? ImageSource is the abstract base class for both of them. If you have a BitmapSource you can convert it to a MemoryStream using:

            private Stream BitmapSourceToStream(BitmapSource writeBmp)
            {
                Stream stream = new MemoryStream();
    
                //BitmapEncoder enc = new PngBitmapEncoder();
                //BitmapEncoder enc = new JpegBitmapEncoder();
                BitmapEncoder enc = new BmpBitmapEncoder();
                enc.Frames.Add(BitmapFrame.Create(writeBmp));
                enc.Save(stream);                                             
    
                return stream;
            }