将IntPtr转换为bitmapimage

时间:2013-05-10 08:53:03

标签: c# wpf image intptr

我使用twain_32进行扫描,并使用twainLib.TransferPictures使用DibToBitmap.FormHDib(hbitmap)bitmapsource获取IntPtr,但我想要bitmapimage

我想直接将IntPtr bitmapsource转换为bitmapimage,而不是bitmapsource然后bitmapimage

3 个答案:

答案 0 :(得分:0)

使用Bitmap Constructor Method

Bitmap newBitmap = new Bitmap(width, height, Stride, PixelFormat, bitmapSource);

答案 1 :(得分:0)

由于您询问的是BitmapSource,并且您的问题已标记为WPF,因此这是避免使用System.Drawing.Bitmap的方法:

Imaging.CreateBitmapSourceFromHBitmap(imagePointer, IntPtr.Zero, Int32Rect.Empty, 
    BitmapSizeOptions.FromEmptyOptions());

您需要使用System.Windows.Interop

答案 2 :(得分:0)

      [DllImport("Kernel32.dll", CharSet = CharSet.Unicode)]
      private static extern IntPtr GlobalLock(IntPtr hMem);

        [DllImport("GdiPlus.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]
        private static extern int GdipCreateBitmapFromGdiDib(IntPtr pBIH, IntPtr pPix, out IntPtr pBitmap);
                public static Bitmap BitmapFromDIB(IntPtr pDIB)
                {
                    IntPtr pPix = (IntPtr)((int)pDIB + 40);
                    IntPtr pBmp = IntPtr.Zero;
                    int status = GdipCreateBitmapFromGdiDib(pDIB, pPix, out pBmp);
                    MethodInfo mi = typeof(Bitmap).GetMethod("FromGDIplus", BindingFlags.Static | BindingFlags.NonPublic);
                    Bitmap bmp = (Bitmap)mi.Invoke(null, new object[] { pBmp });
                    if ((status == 0) && (pBmp != IntPtr.Zero)) return bmp;
                    else return null;
                }

 //   ******
    case TwainCommand.TransferReady:
    {
     ArrayList pics = tw.TransferPictures();
     IntPtr img = (IntPtr)pics[i];
     PicForm newpic = new PicForm();
     var ptrLocked = GlobalLock(img);//lockedptr to image
     newpic.pBox.Image = BitmapFromDIB(ptrLocked); 
     newpic.MdiParent = this;
     int picnum = i + 1;
     newpic.Text = "Picture " + picnumber.ToString();
     newpic.Show();
    }