当前位置:首页 > 编程学习 > 使用C++在控制台界面显示图片

使用C++在控制台界面显示图片

编程学习2021-07-13145151


一直面对黑乎乎的控制台界面是不是很厌烦了?要是控制台界面也能显示图片甚至作为背景是不是很有意思,下面就搞起来。


先来看看效果:

控制台显示图片.png 使用C++在控制台界面显示图片  编程 技术 C++ 第1张


上图是使用VS Code+vc6编译生成的。

下面的代码需要保存为cpp文件,使用C++编译器编译。

#include <windows.h>
#include <stdio.h>

int main()
{
    FILE *file = NULL;
    file = fopen("d:\\Documents\\Desktop\\tt.bmp", "r"); // 只能显示bmp格式图片
    if (!file)
    {
        printf("图片文件打开失败!\n");
        return -1;
    }

    fseek(file, 0, SEEK_END);
    size_t size = ftell(file);

    LPBITMAPINFOHEADER bi = (LPBITMAPINFOHEADER)malloc(size);
    if (!bi)
    {
        printf("内存分配失败!\n");
        return -2;
    }

    fseek(file, sizeof(BITMAPFILEHEADER), SEEK_SET);
    fread(bi, 1, size, file);

    char Title[255] = {0};
    GetConsoleTitleA(Title, 255);
    HDC dc = GetDC(FindWindowA(0, Title));
    SetConsoleTitleA("控制台显示图片");
    
    do
    {        
        SetDIBitsToDevice(dc, 50, 10, bi->biWidth, bi->biHeight, 0, -0, 0, bi->biHeight, bi + 1, (LPBITMAPINFO)bi, 0);
    } while (printf("%c", getchar()));

    getchar();
    return 0;
}


当控制台界面上下滚动时图片会丢失,需要按回车恢复图片显示。

 

 

扫描二维码推送至手机访问。

版权声明:本文由海阔天空发布,如需转载请注明出处。

本文链接:https://apull.net/html/20210713153755.html

标签: 编程技术C++
分享给朋友:

相关文章

VB.NET 用ShellExecuteEx 打开系统文件属性对话框 模块

VB.NET 用ShellExecuteEx 打开系统文件属性对话框 模块

' ' VB.NET 调用系统文件属性对话框模块 ' ' by: Apull ' QQ:374237545 ' http://www.apull.net ' 2007-6-9 ' ' Imports System.Runtime.InteropServices     Mod...

 C++ string类常用函数

C++ string类常用函数

string类的构造函数:string(const char *s);    //用c字符串s初始化 string(int n,char  c);     //用n个字符c初始化此外,string类还支持默认构造函数和复制构造函数,如string s1;string  s2="hello";都是正确的写法。...

VB连接SQLServer数据库操作代码

VB连接SQLServer数据库操作代码

第一步,在ModConString模块中定义一系列变量'定义一个属性过程反映连接字符串Public Property Get conString() As Variant conString = "data source=.;initial catalog=Sims_four;user End Property'定义一个提供者反映数据库类型Public Property Get conProvide() As Variant co...

用VB类实现文件对话框

用VB类实现文件对话框

用VB类实现文件对话框'类名:ComDlg.cls '作用:文件打开保存对话框 ' ' ' 'By:Apull '2007-5-21 'http://www.apull.net Option Explicit Private Declare Function GetOpenFileName Lib "comdlg32.dll" Alias "GetOpenFileNameA" ( _ pOpenfil...