[Win32 C/C++/C#] Drawing text on bitmap and save bitmap to file example code

tom_mai78101

The Helper Connoisseur / Ex-MineCraft Host
Staff member
Reaction score
1,667
This code demonstrates the ability to use Win32 API to draw or print text to a bitmap, and then save the bitmap to a file.

Note:
  • Text is pink for testing purposes.
  • Text font uses the System Font.
  • This is merely a demonstration (proof of concept), and may not be suitable for "best practices".
  • There are many things that can be improved, such as fixing the brief moment where the text would appear on the screen.
  • This program generates a bitmap, akin to doing a Print Screen, which captures the entire screen displayed on your primary monitor.
  • The example code is self-documenting, which is not the best coding practice anyone should follow.
  • The bitmap file, saved after executing the program, is expected to be no less than 8MB at a 1080p resolution.
  • This example code is used for archival purposes, to show that printing text is possible using pure Win32 API in C / C++.
  • There are no AFX or Object-Oriented Win32 stuffs in this code. This is pure Win32 code in C, with very little C++ code in it.

Code:
#include <Windows.h>
#include <iostream>
#include <fstream>

HBITMAP CaptureScreen(HDC currentDeviceContext, std::string text) {
    int width = GetSystemMetrics(SM_CXSCREEN);
    int height = GetSystemMetrics(SM_CYSCREEN);

    HDC compatibleDeviceContext = CreateCompatibleDC(currentDeviceContext);
    HBITMAP bitmapHandle = CreateCompatibleBitmap(currentDeviceContext, width, height);
    HGDIOBJ previousSelectedHandle = SelectObject(compatibleDeviceContext, bitmapHandle);

    BOOL result = BitBlt(compatibleDeviceContext, 0, 0, width, height, currentDeviceContext, 0, 0, SRCCOPY | CAPTUREBLT);
    if (!result) {
        MessageBox(nullptr, TEXT("BitBlt() fails 1."), TEXT("Error"), MB_OK);
        return nullptr;
    }

    HFONT font = (HFONT)GetStockObject(SYSTEM_FONT);
    SetTextColor(compatibleDeviceContext, RGB(255, 0, 255));
    SetBkMode(compatibleDeviceContext, TRANSPARENT);
    HFONT previousFont = (HFONT)SelectObject(compatibleDeviceContext, font);
    TextOut(compatibleDeviceContext, 240, 360, TEXT(text.c_str()), text.size());

    result = BitBlt(currentDeviceContext, 0, 0, width, height, compatibleDeviceContext, 0, 0, SRCCOPY);
    if (!result) {
        MessageBox(nullptr, TEXT("BitBlt() fails 2."), TEXT("Error"), MB_OK);
        return nullptr;
    }

    SelectObject(compatibleDeviceContext, previousFont);
    SelectObject(compatibleDeviceContext, previousSelectedHandle);
    DeleteDC(compatibleDeviceContext);
    return bitmapHandle;
}

void SaveFile(BYTE* pixels, BITMAPINFOHEADER& bitmapInfoHeader) {
    HANDLE fileHandle = CreateFile(TEXT("Test.bmp"), GENERIC_READ | GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
    if (fileHandle == INVALID_HANDLE_VALUE) {
        MessageBox(nullptr, TEXT("CreateFile() failed."), TEXT("Error"), MB_OK);
        return;
    }
    BITMAPFILEHEADER bitmapFileHeader = { 0 };
    bitmapFileHeader.bfType = 0x4d42;
    bitmapFileHeader.bfSize = sizeof(bitmapFileHeader) + bitmapInfoHeader.biSize + bitmapInfoHeader.biClrUsed * sizeof(RGBQUAD) + bitmapInfoHeader.biSizeImage;
    bitmapFileHeader.bfReserved1 = bitmapFileHeader.bfReserved2 = 0;
    bitmapFileHeader.bfOffBits = sizeof(bitmapFileHeader) + bitmapInfoHeader.biSize + bitmapInfoHeader.biClrUsed * sizeof(RGBQUAD);

    DWORD tempDword;
    if (!WriteFile(fileHandle, (LPVOID)&bitmapFileHeader, sizeof(bitmapFileHeader), (LPDWORD)&tempDword, nullptr)) {
        MessageBox(nullptr, TEXT("WriteFile() failed 1."), TEXT("Error"), MB_OK);
        return;
    }

    if (!WriteFile(fileHandle, (LPVOID) &bitmapInfoHeader, sizeof(bitmapInfoHeader) + bitmapInfoHeader.biClrUsed * sizeof(RGBQUAD), (LPDWORD) &tempDword, nullptr)) {
        MessageBox(nullptr, TEXT("WriteFile() failed 2."), TEXT("Error"), MB_OK);
        return;
    }

    if (!WriteFile(fileHandle, (LPVOID) pixels, (int)bitmapInfoHeader.biSizeImage, (LPDWORD) &tempDword, nullptr)) {
        MessageBox(nullptr, TEXT("WriteFile() failed 3."), TEXT("Error"), MB_OK);
        return;
    }

    if (!CloseHandle(fileHandle)) {
        MessageBox(nullptr, TEXT("CloseHandle() failed."), TEXT("Error"), MB_OK);
        return;
    }
}

int main() {
    HDC deviceContext = GetDC(nullptr);
    HBITMAP capturedBitmap = CaptureScreen(deviceContext, std::string("Hello world."));

    BITMAPINFO bitmapInfo = { 0 };
    bitmapInfo.bmiHeader.biSize = sizeof(bitmapInfo.bmiHeader);

    BOOL result = GetDIBits(deviceContext, capturedBitmap, 0, 0, nullptr, &bitmapInfo, DIB_RGB_COLORS);
    if (!result) {
        MessageBox(nullptr, TEXT("GetDIBits() failed."), TEXT("Error"), MB_OK);
        return -1;
    }

    BYTE* pixels = new BYTE[bitmapInfo.bmiHeader.biSizeImage];
    bitmapInfo.bmiHeader.biCompression = BI_RGB;
    result = GetDIBits(deviceContext, capturedBitmap, 0, bitmapInfo.bmiHeader.biHeight, (LPVOID)pixels, &bitmapInfo, DIB_RGB_COLORS);
    if (!result) {
        MessageBox(nullptr, TEXT("GetDIBits(), second function, failed."), TEXT("Error"), MB_OK);
        return -2;
    }

    SaveFile(pixels, bitmapInfo.bmiHeader);

    DeleteObject(capturedBitmap);
    ReleaseDC(nullptr, deviceContext);
    delete[] pixels;
    return 0;
}
 
Last edited:

tom_mai78101

The Helper Connoisseur / Ex-MineCraft Host
Staff member
Reaction score
1,667
The equivalent in C#, except it can:
  • Draw using rectangles with rounded corners, and a solid colored background.
  • Can scale text up or down, depending on how big you want it to be in pixels (px).
  • Can set the canvas size (bitmap size).
  • Can save bitmap to a PNG file.
  • Will always save to Desktop in any operating system.
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Threading.Tasks;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;

namespace csharp_test {
    public static class Extensions {
        public static GraphicsPath RoundedRect(Rectangle bounds, int radius) {
            int diameter = radius * 2;
            Size size = new Size(diameter, diameter);
            Rectangle arc = new Rectangle(bounds.Location, size);
            GraphicsPath path = new GraphicsPath();
            if (radius == 0) {
                path.AddRectangle(bounds);
                return path;
            }
            path.AddArc(arc, 180, 90);
            arc.X = bounds.Right - diameter;
            path.AddArc(arc, 270, 90);
            arc.Y = bounds.Bottom - diameter;
            path.AddArc(arc, 0, 90);
            arc.X = bounds.Left;
            path.AddArc(arc, 90, 90);
            path.CloseFigure();
            return path;

        }

        public static void DrawRoundedRectangle(this Graphics graphics, Pen pen, Rectangle bounds, int cornerRadius) {
            if (graphics == null)
                throw new ArgumentNullException("graphics");
            if (pen == null)
                throw new ArgumentNullException("pen");
            using (GraphicsPath path = RoundedRect(bounds, cornerRadius)) {
                graphics.DrawPath(pen, path);
            }
        }

        public static void FillRoundedRectangle(this Graphics graphics, Brush brush, Rectangle bounds, int cornerRadius) {
            if (graphics == null)
                throw new ArgumentNullException("graphics");
            if (brush == null)
                throw new ArgumentNullException("brush");
            using (GraphicsPath path = RoundedRect(bounds, cornerRadius)) {
                graphics.FillPath(brush, path);
            }
        }
    }

    class Program {
        static void Main(string[] args) {
            int bitmapWidth = 100;
            int bitmapHeight = 100;
            int fontSize = 6;
            string firstText = "This is Hello world.";
            string secondText = "By tom_mai78101";
            string desktopFilePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            string imageFilePath = desktopFilePath + @"\test.png";
            PointF firstLocation = new PointF(10f, 10f);
            PointF secondLocation = new PointF(10f, 50f);
            Bitmap bitmap = new Bitmap(bitmapWidth, bitmapHeight);
            using (Graphics graphics = Graphics.FromImage(bitmap)) {
                using (Font arialFont = new Font("Arial", fontSize)) {
                    Brush brush = new SolidBrush(Color.FromArgb(128, 255, 128));
                    graphics.FillRoundedRectangle(brush, new Rectangle(0, 0, bitmapWidth, bitmapHeight), 24);
                    graphics.DrawString(firstText, arialFont, Brushes.Blue, firstLocation);
                    graphics.DrawString(secondText, arialFont, Brushes.Blue, secondLocation);
                }
            }
            bitmap.Save(imageFilePath, ImageFormat.Png);
        }
    }
}
 
General chit-chat
Help Users
  • No one is chatting at the moment.
  • Varine Varine:
    How can you tell the difference between real traffic and indexing or AI generation bots?
  • The Helper The Helper:
    The bots will show up as users online in the forum software but they do not show up in my stats tracking. I am sure there are bots in the stats but the way alot of the bots treat the site do not show up on the stats
  • Varine Varine:
    I want to build a filtration system for my 3d printer, and that shit is so much more complicated than I thought it would be
  • Varine Varine:
    Apparently ABS emits styrene particulates which can be like .2 micrometers, which idk if the VOC detectors I have can even catch that
  • Varine Varine:
    Anyway I need to get some of those sensors and two air pressure sensors installed before an after the filters, which I need to figure out how to calculate the necessary pressure for and I have yet to find anything that tells me how to actually do that, just the cfm ratings
  • Varine Varine:
    And then I have to set up an arduino board to read those sensors, which I also don't know very much about but I have a whole bunch of crash course things for that
  • Varine Varine:
    These sensors are also a lot more than I thought they would be. Like 5 to 10 each, idk why but I assumed they would be like 2 dollars
  • Varine Varine:
    Another issue I'm learning is that a lot of the air quality sensors don't work at very high ambient temperatures. I'm planning on heating this enclosure to like 60C or so, and that's the upper limit of their functionality
  • Varine Varine:
    Although I don't know if I need to actually actively heat it or just let the plate and hotend bring the ambient temp to whatever it will, but even then I need to figure out an exfiltration for hot air. I think I kind of know what to do but it's still fucking confusing
  • The Helper The Helper:
    Maybe you could find some of that information from AC tech - like how they detect freon and such
  • Varine Varine:
    That's mostly what I've been looking at
  • Varine Varine:
    I don't think I'm dealing with quite the same pressures though, at the very least its a significantly smaller system. For the time being I'm just going to put together a quick scrubby box though and hope it works good enough to not make my house toxic
  • Varine Varine:
    I mean I don't use this enough to pose any significant danger I don't think, but I would still rather not be throwing styrene all over the air
  • The Helper The Helper:
    New dessert added to recipes Southern Pecan Praline Cake https://www.thehelper.net/threads/recipe-southern-pecan-praline-cake.193555/
  • The Helper The Helper:
    Another bot invasion 493 members online most of them bots that do not show up on stats
  • Varine Varine:
    I'm looking at a solid 378 guests, but 3 members. Of which two are me and VSNES. The third is unlisted, which makes me think its a ghost.
    +1
  • The Helper The Helper:
    Some members choose invisibility mode
    +1
  • The Helper The Helper:
    I bitch about Xenforo sometimes but it really is full featured you just have to really know what you are doing to get the most out of it.
  • The Helper The Helper:
    It is just not easy to fix styles and customize but it definitely can be done
  • The Helper The Helper:
    I do know this - xenforo dropped the ball by not keeping the vbulletin reputation comments as a feature. The loss of the Reputation comments data when we switched to Xenforo really was the death knell for the site when it came to all the users that left. I know I missed it so much and I got way less interested in the site when that feature was gone and I run the site.
  • Blackveiled Blackveiled:
    People love rep, lol
    +1
  • The Helper The Helper:
    The recipe today is Sloppy Joe Casserole - one of my faves LOL https://www.thehelper.net/threads/sloppy-joe-casserole-with-manwich.193585/
  • The Helper The Helper:
    Decided to put up a healthier type recipe to mix it up - Honey Garlic Shrimp Stir-Fry https://www.thehelper.net/threads/recipe-honey-garlic-shrimp-stir-fry.193595/

      The Helper Discord

      Members online

      No members online now.

      Affiliates

      Hive Workshop NUON Dome World Editor Tutorials

      Network Sponsors

      Apex Steel Pipe - Buys and sells Steel Pipe.
      Top