Bitmap转ImageSource

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

你可能感兴趣的:(Bitmap转ImageSource)