How do you copy a Graphic to a Bitmap Image?

  • Thread starter Thread starter icepick72
  • Start date Start date
I

icepick72

On an academic note, I want to copy a Graphic to an Image (Bitmap).
I have the Graphic object but not the origin image from which it
originates; this is because I'm overriding the PrintDocument class
OnPagePrint method which only provides me an e.Graphic (see code
sample below).

The FCL doesn't seem to natively support Graphic => (Image)Bitmap. I
have tried BitBlt workaround in the source code to copy printer
e.Graphic into the bmp Graphic, but the bitmap ends up being blank
even thought the printer Graphic is not.
Any thoughts as to a resolution?

using System;
using System.Windows.Forms;

using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Printing;

namespace RemotePrinting
{
class PicDocumentPrinter : PrintDocument
{
private Image _bmpOfPage = null;


// When the page is printed.
protected override void OnPrintPage(PrintPageEventArgs e)
{
// Draw an ellipse on printer Graphic so we have something
to see.
e.Graphics.DrawEllipse(new Pen(Color.Blue, 5), 0, 0, 100,
100);

// Create bitmap Image.
Bitmap bmp = new Bitmap(500,500, e.Graphics);
Graphics gfxBmp = Graphics.FromImage(bmp);

IntPtr hdcPrint = e.Graphics.GetHdc();
IntPtr hdcBmp = gfxBmp.GetHdc();

/* Try to copy printer e.Graphic onto Bitmap Graphic.
* The bitmap will be blank -- why did the ellipse not
copy?
* The printer shows the ellipse.
*/
BitBlt(hdcBmp, 0, 0, 500, 500, hdcPrint, 0, 0, SRCCOPY);

gfxBmp.ReleaseHdc(hdcBmp);
e.Graphics.ReleaseHdc(hdcPrint);


e.HasMorePages = false;

// This bmp is blank, but should not be.
_bmpOfPage = bmp;
}

public Image Result
{
get { return _bmpOfPage; }
}

int SRCCOPY = 13369376;

[System.Runtime.InteropServices.DllImport("GDI32.DLL", CharSet
= System.Runtime.InteropServices.CharSet.Auto)]
private static extern bool BitBlt(IntPtr hdcDest, int nXDest,
int nYDest, int nWidth, int nHeight, IntPtr hdcSrc, int nXSrc, int
nYSrc, Int32 dwRop);

}
}
 
You might get more response if you post to
microsoft.public.dotnet.framework.drawing.

Robin S.
 
Back
Top