Bitmap転送ImageSource

1400 ワード

bitmap to bytes
Bitmap   b   =   new   Bitmap( "test.bmp "); 
MemoryStream   ms   =   new   MemoryStream(); 
b.Save(ms,System.Drawing.Imaging.ImageFormat.Bmp); 
byte[]   bytes=   ms.GetBuffer();  //byte[]   bytes=   ms.ToArray();  , , 
ms.Close(); 

bytes to bitmap
byte[]   bytelist=bytes; 
MemoryStream   ms1   =   new   MemoryStream(bytelist); 
Bitmap   bm   =   (Bitmap)Image.FromStream(ms1); 
ms1.Close(); 
public static ImageSource ChangeBitmapToImageSource(Bitmap bitmap)
        {
            //Bitmap bitmap = icon.ToBitmap();  
            IntPtr hBitmap = bitmap.GetHbitmap();

            // , , background, gdi32.dll DeleteObject 

            ImageSource wpfBitmap = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                hBitmap,
                IntPtr.Zero,
                Int32Rect.Empty,
                BitmapSizeOptions.FromEmptyOptions());
            if (!DeleteObject(hBitmap))
            {
                throw new System.ComponentModel.Win32Exception();
            }
            return wpfBitmap;
        }
var img = new ImageBrush();
img.ImageSource = new BitmapImage(new Uri($"{AppDomain.CurrentDomain.BaseDirectory}\\xxx.bmp",
UriKind.Absolute));
bd.Background = img;

転載先:https://www.cnblogs.com/HaibaraAi/p/6951352.html