最近在尝试Direct2D编程,挺好玩的。
但是有时候还是会用到GDI+来生成图片,但D2D绘图需要用到自己的D2DBitmap类。
因此需要转换,查阅了下网上的资料,写了这么一个方法:
1 using System; 2 using System.Windows.Forms; 3 using System.Linq; 4 using System.Text; 5 using System.Diagnostics; 6 using DX = SharpDX; 7 using D2D = SharpDX.Direct2D1; 8 using WIC = SharpDX.WIC; 9 using DDW = SharpDX.DirectWrite; 10 using DXGI = SharpDX.DXGI; 11 using SharpDX; 12 13 public D2D.Bitmap ConvertFromSystemBitmap(System.Drawing.Bitmap bmp) 14 { 15 System.Drawing.Bitmap desBitmap;//预定义要是使用的bitmap 16 //如果原始的图像像素格式不是32位带alpha通道 17 //需要转换为32位带alpha通道的格式 18 //否则无法和Direct2D的格式对应 19 if (bmp.PixelFormat != System.Drawing.Imaging.PixelFormat.Format32bppPArgb) 20 { 21 desBitmap = new System.Drawing.Bitmap(bmp.Width, bmp.Height, System.Drawing.Imaging.PixelFormat.Format32bppPArgb); 22 using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(desBitmap)) 23 { 24 g.DrawImage(bmp, 0, 0); 25 } 26 } 27 else 28 { 29 desBitmap = bmp; 30 } 31 32 33 //直接内存copy会非常快 34 //如果使用循环逐点转换会非常慢 35 System.Drawing.Imaging.BitmapData bmpData = desBitmap.LockBits( 36 new System.Drawing.Rectangle(0, 0, desBitmap.Width, desBitmap.Height), 37 System.Drawing.Imaging.ImageLockMode.ReadOnly, 38 desBitmap.PixelFormat 39 ); 40 int numBytes = bmpData.Stride * desBitmap.Height; 41 byte[] byteData = new byte[numBytes]; 42 IntPtr ptr = bmpData.Scan0; 43 System.Runtime.InteropServices.Marshal.Copy(ptr, byteData, 0, numBytes); 44 desBitmap.UnlockBits(bmpData); 45 46 47 48 D2D.BitmapProperties bp; 49 D2D.PixelFormat pixelFormat = new D2D.PixelFormat(DXGI.Format.B8G8R8A8_UNorm, D2D.AlphaMode.Premultiplied); 50 51 bp = new D2D.BitmapProperties( 52 pixelFormat, 53 desBitmap.HorizontalResolution, 54 desBitmap.VerticalResolution 55 ); 56 D2D.Bitmap tempBitmap = new D2D.Bitmap(_renderTarget, new Size2(desBitmap.Width, desBitmap.Height), bp); 57 tempBitmap.CopyFromMemory(byteData, bmpData.Stride); 58 59 return tempBitmap; 60 }
PS.这里我用的是SharpDX组件,因为微软的Windows API Code Pack,只更新到1.1,2010年后就不维护了
时间: 2024-10-24 13:18:26