Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert D3DImage to byte array

Tags:

c#

wpf

d3dimage

Is there any way to do that ?

I can cast the object to ImageSource and assign to Image but I have to be able to store it in byte[]. All the methods I found use casting to BitMap and that won't work here.

like image 607
cah1r Avatar asked Dec 12 '25 09:12

cah1r


1 Answers

Here is a solution I found. The key was the use of DrawingVisual to create temporary image internally.

        public static byte[] ImageToBytes(ImageSource imageSource)
    {
        var bitmapSource = imageSource as BitmapSource;
        if (bitmapSource == null)
        {
            var width = (int)imageSource.Width;
            var height = (int)imageSource.Height;
            var dv = new DrawingVisual();
            using (var dc = dv.RenderOpen())
            {
                dc.DrawImage(imageSource, new Rect(0, 0, width, height));
            }
            var rtb = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Pbgra32);
            rtb.Render(dv);
            bitmapSource = BitmapFrame.Create(rtb);
        }

        byte[] data;
        var encoder = new PngBitmapEncoder();
        encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
        using (var ms = new MemoryStream())
        {
            encoder.Save(ms);
            data = ms.ToArray();
        }
        return data;
    }
like image 111
cah1r Avatar answered Dec 14 '25 22:12

cah1r



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!