如何在 BGR 图像的像素上绘制一串文本,以便文本在显示时可读,C++?

问题描述 投票:0回答:2

有没有一种简单的方法可以修改 72x72 像素 BGR 图像的像素,使其包含显示图像时可读的文本字符串。

本质上,我需要在下面创建的图像缓冲区

str
上绘制
img
中的文本,以便在显示图像时可以读取文本。

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?
c++ image draw
2个回答
1
投票

我建议像这样CImg

#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

它体积小,速度快,功能全面,现代 C++ 和 “仅标头”这意味着您也不需要链接任何东西。


0
投票

所选答案对我来说太复杂了!代码行太多...

Github 提供了 8x8 字体:https://github.com/dhepper/font8x8

以下是下载font8x8_basic.h后的代码: https://raw.githubusercontent.com/dhepper/font8x8/refs/heads/master/font8x8_basic.h

//wget https://raw.githubusercontent.com/dhepper/font8x8/refs/heads/master/font8x8_basic.h
//gcc a.c && ./a.out

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "font8x8_basic.h"

void draw_text(unsigned char *data, int width, int height, int posx, int posy, const char *text) {
    int i, x, y;
    for (i = 0; text[i] != '\0'; i++)
        for (y = 0; y < 8; y++)
            for (x = 0; x < 8; x++)
            if (font8x8_basic[text[i]][y] & (1 << x)) {
                data[3 * ((posy + y) * width + posx + x + 8 * i) + 0] = 255;
                data[3 * ((posy + y) * width + posx + x + 8 * i) + 1] = 255;
                data[3 * ((posy + y) * width + posx + x + 8 * i) + 2] = 255;
            }
}

int main() {
    int width = 1280;
    int height = 720;
    unsigned char *data = malloc(width * height * 3);
    memset(data, 0, width * height * 3);
    draw_text(data, width, height, 50, 50, "Hello, World!");
    FILE *pf = fopen("a.rgb", "w");
    fwrite(data, width * height * 3, 1, pf);
    fclose(pf);
    free(data);
    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.