请问C++有没有一种方法加载png图片,无论exe文件复制到哪都可以用

请问C++有没有一种方法加载png图片,无论exe文件复制到哪都可以用,第1张

VC6工程,刚写的示例代码。注意工程中所有“注意这里”的注释和View里的OnDraw函数

用嵌入资源的方式把PNG塞入EXE文件中,只要复制一个EXE文件即可使用。

使用GDIPLUS加载和显示,VC6需要安装Gdiplus开发包,没安装会编译错误。

对了忘了说了,图片在res文件夹里

使用 stb_image 库将图像文件作为C/C++数组编译进程序中,需要以下几个步骤:

下载 stb_image 库的源代码,并将 stb_image.h 文件包含到您的项目中。可以从以下网址下载:https://github.com/nothings/stb/blob/master/stb_image.h

使用 stbi_load_from_memory 函数从图像文件中加载图像数据,该函数可以将文件数据加载到内存中,返回指向图像数据的指针,以及图像的宽度、高度和通道数。

将图像数据转换为C/C++数组,并将其存储在静态变量中。

以下是示例代码:

#define STB_IMAGE_IMPLEMENTATION

#include "stb_image.h"

static unsigned char image_data[] = {

// Insert image data here

}

static int image_width = 0

static int image_height = 0

static int image_channels = 0

void load_image_from_memory(const unsigned char* data, int size) {

unsigned char* image =

stbi_load_from_memory(data, size, &image_width, &image_height,

&image_channels, STBI_rgb_alpha)

if (image != nullptr) {

size_t data_size = image_width * image_height * image_channels

memcpy(image_data, image, data_size)

stbi_image_free(image)

}

}

在上面的代码中,load_image_from_memory 函数使用 stbi_load_from_memory 函数从内存中加载图像数据,并将其存储在 image_data 静态变量中。使用 memcpy 函数将从文件中加载的图像数据复制到 image_data 中。可以在程序中调用 load_image_from_memory 函数来加载图像数据,并将其作为纹理绘制到屏幕上。

要将图像文件嵌入到程序中,可以使用文件工具将文件转换为C/C++数组,例如 xxd、bin2h 等。在将图像数据存储到数组中时,需要使用十六进制格式。例如,下面的命令可以将图像文件转换为C/C++数组:

$ xxd -i image.png >image_data.h

该命令将图像文件 image.png 转换为C/C++数组,并将其存储在 image_data.h 文件中。将 image_data.h 文件包含到您的项目中,并在程序中调用 load_image_from_memory 函数以加载图像数据。

注意,在将图像嵌入到程序中时,需要考虑到图像文件的大小,如果图像文件太大,可能会导致程序的体积变得非常大。建议将小型图像文件嵌入到程序中,对于大型图像文件,最好将其作为外部资源加载。


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/yw/12003312.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-20
下一篇 2023-05-20

发表评论

登录后才能评论

评论列表(0条)

保存