c++imagedraw

How can I draw a string of text onto the pixels of a BGR image so that the text is readable when displayed, c++?


Is there a simple way to modify the pixels of a 72x72 pixel BGR image so that it contains a string of text that is readable when the image is displayed.

Essentially, I need to draw the text in str on the image buffer img created below in a way that would allow it to be read when the image is displayed.

unsigned char img[72*72*3]; // 72*72*3 BGR image buffer
unsigned char B = 0x00; 
unsigned char G = 0x00;
unsigned char R = 0x00;
std::string str = "Test Text";

// Create BGR image
for (int i = 0; i < (72*72*3); i += 3)
{
    img[i + 0] = B;
    img[i + 1] = G;
    img[i + 2] = R;
}

// Draw str on BGR image buffer?

Solution

  • I would suggest CImg like this:

    #include <iostream>
    #include <cstdlib>
    #define cimg_display 0
    #include "CImg.h"
    
    using namespace cimg_library;
    using namespace std;
    
    int main() {
       // Create 72x72 RGB image
       CImg<unsigned char> image(72,72,1,3);
    
       // Fill with magenta
       cimg_forXY(image,x,y) {
          image(x,y,0,0)=255;
          image(x,y,0,1)=0;
          image(x,y,0,2)=255;
       }
    
       // Make some colours
       unsigned char cyan[]    = {0,   255, 255 };
       unsigned char black[]   = {0,   0,   0   };
    
       // Draw black text on cyan
       image.draw_text(3,20,"Test text",black,cyan,1,16);
    
       // Save result image as NetPBM PNM - no libraries required
       image.save_pnm("result.pnm");
    }
    

    enter image description here

    It is small, fast, comprehensive in terms of functionality, modern C++ and "header only" which means you don't need to link against anything either.