Click here to Skip to main content
15,886,362 members
Articles / Desktop Programming / MFC

Saving a Drawing to a Bitmap File

Rate me:
Please Sign up or sign in to vote.
4.33/5 (24 votes)
18 Jan 20053 min read 179.7K   8.5K   75  
A simple way to save a drawing to a bitmap file.
// Drawing2BitmapDlg.cpp : implementation file
//

#include "stdafx.h"
#include "Drawing2Bitmap.h"
#include "Drawing2BitmapDlg.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	//{{AFX_DATA(CAboutDlg)
	enum { IDD = IDD_ABOUTBOX };
	//}}AFX_DATA

	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CAboutDlg)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL

// Implementation
protected:
	//{{AFX_MSG(CAboutDlg)
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	//{{AFX_DATA_INIT(CAboutDlg)
	//}}AFX_DATA_INIT
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAboutDlg)
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
	//{{AFX_MSG_MAP(CAboutDlg)
		// No message handlers
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CDrawing2BitmapDlg dialog

CDrawing2BitmapDlg::CDrawing2BitmapDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CDrawing2BitmapDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CDrawing2BitmapDlg)
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
	/////////////////////////////////////////////////////////////////////////
	m_rDrawingSurface = CRect(0, 0, 0, 0);
	m_crBackgroundColor = RGB(255, 255, 255);
	m_crPenColor = RGB(0, 0, 255);
	m_nPenStyle = PS_SOLID;
	m_nPenWidth = 2;
	m_hDrawingSurface = NULL;
	m_pDrawingSurfaceBits = NULL;
	memset(&BMIH, 0, sizeof(BITMAPINFOHEADER));
	////////////////////////////////////////////////////////////////////////
	m_bIsCreatingPath = FALSE;
	m_pCurrentPath = NULL;
	////////////////////////////////////////////////////////////////////////
}

void CDrawing2BitmapDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CDrawing2BitmapDlg)
	DDX_Control(pDX, IDC_DRAWING_SURFACE, DrawingSurface);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CDrawing2BitmapDlg, CDialog)
	//{{AFX_MSG_MAP(CDrawing2BitmapDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(ID_SAVE, OnSave)
	ON_WM_LBUTTONDOWN()
	ON_WM_LBUTTONUP()
	ON_WM_MOUSEMOVE()
	ON_WM_DESTROY()
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CDrawing2BitmapDlg message handlers

BOOL CDrawing2BitmapDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	/////////////////////////////////////////////////////////////////////////////////////
	//Get the drawing surface and create a corresponding bitmap with the same dimensions
	DrawingSurface.GetWindowRect(&m_rDrawingSurface);
	ScreenToClient(&m_rDrawingSurface);
	CDC* pDC = GetDC();
	if(pDC != NULL)
	{
		BMIH.biSize = sizeof(BITMAPINFOHEADER);
		BMIH.biBitCount = 24;
		BMIH.biPlanes = 1;
		BMIH.biCompression = BI_RGB;
		BMIH.biWidth = m_rDrawingSurface.Width();
		BMIH.biHeight = m_rDrawingSurface.Height();
		BMIH.biSizeImage = ((((BMIH.biWidth * BMIH.biBitCount) + 31) & ~31) >> 3) * BMIH.biHeight;
		m_hDrawingSurface = CreateDIBSection(pDC->GetSafeHdc(), (CONST BITMAPINFO*)&BMIH, DIB_RGB_COLORS, (void**)&m_pDrawingSurfaceBits, NULL, 0);
		ReleaseDC(pDC);
	}
	/////////////////////////////////////////////////////////////////////////////////////	
	if((m_hDrawingSurface == NULL) || (m_pDrawingSurfaceBits == NULL))
	{
		//We could not create the bitmap -- quit
		AfxMessageBox(IDS_BITMAP_NOT_CREATED_ERROR_MESSAGE, MB_OK | MB_ICONSTOP);
		PostQuitMessage(0);
	}
	/////////////////////////////////////////////////////////////////////////////////////
	return TRUE;  // return TRUE  unless you set the focus to a control
}


void CDrawing2BitmapDlg::Draw()
{
	CDC* pDC = GetDC();
	if(pDC != NULL)
	{
		CDC dcMem;
		//Create a memory dc and select the drawing surface into it
		if(dcMem.CreateCompatibleDC(pDC) == TRUE)
		{
			HBITMAP hOldBitmap = (HBITMAP)SelectObject(dcMem.GetSafeHdc(), m_hDrawingSurface);	
			/////////////////////////////////////////////////////////////////////////////////////
			//Once out drawing surface has been selected into the memory dc, we can draw anything 
			//and have it all nicely collected in our bitmap for future use
			//Fill up the background
			dcMem.FillSolidRect(0, 0, m_rDrawingSurface.Width(), m_rDrawingSurface.Height(), m_crBackgroundColor);
			//Now create and select the pen into the memory dc, extract the paths and draw them
			CPen ThePen(m_nPenStyle, m_nPenWidth, m_crPenColor);
			CPen* pOldPen = dcMem.SelectObject(&ThePen);

			int nPathCount = m_paPathList.GetSize();
			for(int i = 0; i < nPathCount; i++)
			{
				CPath* pPath = (CPath*)m_paPathList.GetAt(i);
				if(pPath != NULL)
					pPath->Draw(&dcMem);
			}
			dcMem.SelectObject(pOldPen);
			//Now blit our memory drawing to the static control's rectangle
			BOOL bResult = BitBlt(pDC->GetSafeHdc(), 
								  m_rDrawingSurface.left,
								  m_rDrawingSurface.top,
								  m_rDrawingSurface.Width(),
								  m_rDrawingSurface.Height(),
								  dcMem.GetSafeHdc(),
								  0,
								  0,
								  SRCCOPY);
			//And deselect the drawing surface
			SelectObject(dcMem.GetSafeHdc(), hOldBitmap);
			/////////////////////////////////////////////////////////////////////////////////////
		}
		ReleaseDC(pDC);
	}
}

void CDrawing2BitmapDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CDrawing2BitmapDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
		//Perform our own drawing
		Draw();
	}
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CDrawing2BitmapDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

void CDrawing2BitmapDlg::OnSave() 
{
	CString szFilter;
	szFilter.LoadString(IDS_WINDOWS_BITMAP_FILES);
	//Display the "Save As" dialog for the user to specify a path name
	CFileDialog dlg(FALSE, DEFAULT_BITMAP_FILE_EXTENSION, DEFAULT_BITMAP_FILE_NAME, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, szFilter, NULL);
	if(dlg.DoModal() == IDOK)
	{
		CString szPathName = dlg.GetPathName();
		//Create a new file for writing
		FILE *pFile = fopen(szPathName, "wb");
		if(pFile == NULL)
		{
			AfxMessageBox(IDS_FILE_CREATE_ERROR_MESSAGE);
			return;
		}
		BITMAPFILEHEADER bmfh;	
		int nBitsOffset = sizeof(BITMAPFILEHEADER) + BMIH.biSize; 
		LONG lImageSize = BMIH.biSizeImage;
		LONG lFileSize = nBitsOffset + lImageSize;
		bmfh.bfType = 'B'+('M'<<8);			
		bmfh.bfOffBits = nBitsOffset;		
		bmfh.bfSize = lFileSize;				
		bmfh.bfReserved1 = bmfh.bfReserved2 = 0;
		//Write the bitmap file header
		UINT nWrittenFileHeaderSize = fwrite(&bmfh, 1, sizeof(BITMAPFILEHEADER), pFile);
		//And then the bitmap info header
		UINT nWrittenInfoHeaderSize = fwrite(&BMIH, 1, sizeof(BITMAPINFOHEADER), pFile);
		//Finally, write the image data itself -- the data represents our drawing
		UINT nWrittenDIBDataSize = fwrite(m_pDrawingSurfaceBits, 1, lImageSize, pFile);
		
		fclose(pFile);		
	}	
}

void CDrawing2BitmapDlg::OnLButtonDown(UINT nFlags, CPoint point) 
{
	//See if the mouse is within the drawing surface
	if(m_rDrawingSurface.PtInRect(point) == TRUE)
	{		
		//Create a new path and add it to our path list
		m_pCurrentPath = new CPath;
		if(m_pCurrentPath != NULL)
		{
			/////////////////////////////////////////////////////////////////////////
			m_paPathList.Add(m_pCurrentPath);
			/////////////////////////////////////////////////////////////////////////
			m_bIsCreatingPath = TRUE;
			SetCapture();
			CRect rClip;
			DrawingSurface.GetWindowRect(&rClip);
			ClipCursor(&rClip);			
		}
	}
	CDialog::OnLButtonDown(nFlags, point);
}

void CDrawing2BitmapDlg::OnLButtonUp(UINT nFlags, CPoint point) 
{
	if(m_bIsCreatingPath == TRUE)
	{
		//Release the mouse and input focus
		m_bIsCreatingPath = FALSE;
		ReleaseCapture();
		ClipCursor(NULL);	
	}
	CDialog::OnLButtonUp(nFlags, point);
}

void CDrawing2BitmapDlg::OnMouseMove(UINT nFlags, CPoint point) 
{
	if((m_bIsCreatingPath == TRUE) && (m_pCurrentPath != NULL))
	{
		//Add this point to our current path
		CPoint* pPoint = new CPoint(point);
		if(pPoint != NULL)
		{
			//Translate the point to fit within the drawing surface
			pPoint->Offset(-m_rDrawingSurface.left, -m_rDrawingSurface.top);
			m_pCurrentPath->AddPoint(pPoint);
		}
		//Then update the drawing
		Draw();
	}
	CDialog::OnMouseMove(nFlags, point);
}

void CDrawing2BitmapDlg::OnDestroy() 
{
	//Delete any paths we have
	int nPathCount = m_paPathList.GetSize();
	for(int i = 0; i < nPathCount; i++)
	{
		CPath* pPath = (CPath*)m_paPathList.GetAt(i);
		if(pPath != NULL)
		{
			delete pPath;
			pPath = NULL;
		}
	}
	m_paPathList.RemoveAll();
	//Delete the bitmap we created
	if(m_hDrawingSurface != NULL)
	{
		DeleteObject(m_hDrawingSurface);
		m_hDrawingSurface = NULL;
	}

	CDialog::OnDestroy();	
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
President Imatronics Corporation
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions