none
Convert Graphics to Bitmap RRS feed

  • Question

  • Hi,

    I need help to convert a Graphics to a bitmap.
    I retrieve a Graphics like this :

    Code Snippet

    Graphics g = Graphics.FromHdc(IntPtrOfForm);


    And i want to convert it to a Bitmap

    Is it possible ?

    Thanks

    Wednesday, November 19, 2008 4:10 PM

Answers

  • Hi Nen,

     

    If you import the BitBlt-Function from coredll it's no real problem:

     

    Code Snippet

    [DllImport("coredll.dll", SetLastError = true)]

    internal static extern bool BitBlt(IntPtr hDest, int nDstX, int nDstY, int nWidth, int nHeight, IntPtr hSrc, int nSrcX, int nSrcY, uint BitBltOperation);

     

    void SaveAsBitmap(Graphics gxSrc, int sizeX, int SizeY)

    {

    Bitmap bm = new Bitmap(sizeX, sizeY);

    Graphics gxDst = Graphics.FromImage(bm);

    IntPtr hSrc = gxSrc.GetHdc();

    IntPtr hDst = gxDst.GetHdc();

    BitBlt(hDst, 0, 0, sizeX, sizeY, hSrc, 0, 0, 0xcc0020); // SourceCopy operation

    gxDst.ReleaseHdc(hDst);

    gxSrc.ReleaseHdc(hSrc);

    gxDst.Dispose();

    bm.Save("\\temp\\test.bmp", System.Drawing.Imaging.ImageFormat.Bmp);

    bm.Dispose();

    }

     

     

    Hope it helps,

     

    Ulrich

     

    Thursday, November 20, 2008 12:17 PM

All replies

  • Hi Nen,

     

    If you import the BitBlt-Function from coredll it's no real problem:

     

    Code Snippet

    [DllImport("coredll.dll", SetLastError = true)]

    internal static extern bool BitBlt(IntPtr hDest, int nDstX, int nDstY, int nWidth, int nHeight, IntPtr hSrc, int nSrcX, int nSrcY, uint BitBltOperation);

     

    void SaveAsBitmap(Graphics gxSrc, int sizeX, int SizeY)

    {

    Bitmap bm = new Bitmap(sizeX, sizeY);

    Graphics gxDst = Graphics.FromImage(bm);

    IntPtr hSrc = gxSrc.GetHdc();

    IntPtr hDst = gxDst.GetHdc();

    BitBlt(hDst, 0, 0, sizeX, sizeY, hSrc, 0, 0, 0xcc0020); // SourceCopy operation

    gxDst.ReleaseHdc(hDst);

    gxSrc.ReleaseHdc(hSrc);

    gxDst.Dispose();

    bm.Save("\\temp\\test.bmp", System.Drawing.Imaging.ImageFormat.Bmp);

    bm.Dispose();

    }

     

     

    Hope it helps,

     

    Ulrich

     

    Thursday, November 20, 2008 12:17 PM
  • Hi Ulrich,

    It works very well !!

    Thank you very much for your help !

    Nen
    Thursday, November 20, 2008 2:53 PM