byte[] GenerateByteArrayFromBitmapHandle(IntPtr bitmapHandle) { var bitmap = new IconNativeApi.BITMAP(); AllocateBitmapSpace(bitmapHandle, ref bitmap); try { FillBitmapBitsIntoHandle(bitmap); var bitmapSource = CreateBitmapSourceFromHandle(bitmapHandle, bitmap); return imagePersistenceService.ConvertBitmapSourceToByteArray(bitmapSource); } finally { iconNativeApi.DeleteObject(bitmapHandle); } }
byte[] GenerateByteArrayFromBitmapHandle(IntPtr bitmapHandle) { var bitmap = new IconNativeApi.BITMAP(); AllocateBitmapSpace(bitmapHandle, ref bitmap); try { FillBitmapBitsIntoHandle(bitmap); var bitmapSource = CreateBitmapSourceFromHandle(bitmapHandle, bitmap); return(imagePersistenceService.ConvertBitmapSourceToByteArray(bitmapSource)); } finally { iconNativeApi.DeleteObject(bitmapHandle); } }
static BitmapSource CreateBitmapSourceFromHandle(IntPtr bitmapHandle, IconNativeApi.BITMAP bitmap) { var bitmapSource = Imaging.CreateBitmapSourceFromHBitmap( bitmapHandle, IntPtr.Zero, new Int32Rect( 0, 0, bitmap.Width, bitmap.Height), BitmapSizeOptions .FromWidthAndHeight( bitmap .Width, bitmap .Height)); bitmapSource.Freeze(); return(bitmapSource); }
void AllocateBitmapSpace(IntPtr bitmapHandle, ref IconNativeApi.BITMAP bitmap) { var bufferSize = Marshal.SizeOf(bitmap); iconNativeApi.GetObject(bitmapHandle, bufferSize, out bitmap); }
static void FillBitmapBitsIntoHandle(IconNativeApi.BITMAP bitmap) { var bytes = new byte[bitmap.WidthBytes * bitmap.Height]; Marshal.Copy(bitmap.Bits, bytes, 0, bytes.Length); }