James Hoi's Blog

C语言实现命令行显示图片

Word count: 420Reading time: 2 min
2021/05/10 Share

加载本地图片

参考了https://kc.kexinshe.com/t/81443文章

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <windows.h>
#include <conio.h>

int main()
{
// 隐藏光标
CONSOLE_CURSOR_INFO curinfo = { sizeof curinfo, FALSE };
SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &curinfo);
// 获取控制台窗口句柄
HWND hwnd = GetForegroundWindow();
// 获取绘图句柄
HDC hdc = GetDC(hwnd);
//获取客户区大小
RECT rc; GetClientRect(hwnd, &rc);
// 循环绘图
while (TRUE)
{
// 选择TrueType字体
SelectObject(hdc, GetStockObject(DEFAULT_GUI_FONT));
// 加载本地HBITMAP
HBITMAP hbm = (HBITMAP)LoadImage(NULL, "pic2.bmp", IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
// 缓冲绘图句柄,将hbm存入句柄中
HDC buffer = CreateCompatibleDC(NULL); SelectObject(buffer, hbm);
// 获取图片大小
BITMAP bitmapInfo; GetObject(hbm, sizeof(BITMAP),&bitmapInfo);
// 把hbm画到命令行中
BitBlt(hdc, 0, 0, bitmapInfo.bmWidth, bitmapInfo.bmHeight, buffer, 0, 0, SRCCOPY);
//释放图片空间,否则内存占用空间非常大
DeleteObject(hbm);
// 刷新频率10Hz
Sleep(100);
}
// 释放绘图句柄并清空命令列表
ReleaseDC(hwnd, hdc);
return 0;
}

image.png

将像素点转HBitmap并画图

参考这个https://stackoverflow.com/questions/15930528/how-to-convert-an-array-of-pixels-to-hbitmap,把生成的HBitmap用上面的方法画图即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
HBITMAP LoadPic(HDC hdc) {
BITMAPINFOHEADER bmih;
bmih.biSize = sizeof(BITMAPINFOHEADER);
bmih.biWidth = 540;
bmih.biHeight = 541;
bmih.biPlanes = 1;
bmih.biBitCount = 24;
bmih.biCompression = BI_RGB;
bmih.biSizeImage = 0;
bmih.biXPelsPerMeter = 10;
bmih.biYPelsPerMeter = 10;
bmih.biClrUsed = 0;
bmih.biClrImportant = 0;

BITMAPINFO dbmi;
ZeroMemory(&dbmi, sizeof(dbmi));
dbmi.bmiHeader = bmih;
dbmi.bmiColors->rgbBlue = 0;
dbmi.bmiColors->rgbGreen = 0;
dbmi.bmiColors->rgbRed = 0;
dbmi.bmiColors->rgbReserved = 0;

void* bits = (void*)&(imgData[0]);//BMP图片像素点,注意是BGR格式并非RGB
HBITMAP hBitmap = CreateDIBSection(hdc, &dbmi, DIB_RGB_COLORS, &bits, NULL, 0);
memcpy(bits, imgData, sizeof(imgData));
return hBitmap;
}
//记得调用完此函数后要释放HBITMAP的空间,否则内存占用非常大
//DeleteObject(hbm);

若对BMP读写有问题可以参考我的另外一篇文章
https://www.yuque.com/jameshoi/default/bmp

CATALOG
  1. 1. 加载本地图片
  2. 2. 将像素点转HBitmap并画图