stb 下载
stb 是一个非常好用的lib, 本身只需要头文件就行,MIT协议,可以商用
用它做OPENGL 3d engine的读取库是很合适。如png图像,RGBA,四通道图像读取,并且修改像素,如制作一个地图,使用修改像素的方法直接标识地点
#include <stdio.h>
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
int main(int argc, char** argv)
{
int w, h, n;
unsigned char *data = stbi_load("1.png", &w, &h, &n, 0);
cout<<"w is :"<<w <<" h is :"<< h<<" channel is :"<< n <<endl;
//rgba,write 10 red pixel at line 11
for (int dx = 0; dx < 10; ++dx)
{
data[n * w * 10 + dx * n + 0] = 255;
data[n * w * 10 + dx * n + 1] = 0;
data[n * w * 10 + dx * n + 2] = 0;
data[n * w * 10 + dx * n + 3] = 255;
}
//write image
stbi_write_png("write.png", w, h, n, data, w * n);
stbi_image_free(data);
return 0;
}
可以直接存也可以直接从内存中把图像给opengl贴图就行
void load_mem()
{
FILE* inFile = fopen("test.png", "rb");
fseek(inFile, 0, SEEK_END);
unsigned int bufSize = ftell(inFile);
fseek(inFile, 0, SEEK_SET);
unsigned char* buf = new unsigned char[bufSize];
fread(buf, bufSize, 1, inFile);
fclose(inFile);
int w = 128;
int h = 128;
int n = 4;
unsigned char *rgba = stbi_load_from_memory(buf, bufSize, &w, &h, &n, 0);
stbi_write_png("memory.png", w, h, n, rgba, w * n);
stbi_image_free(rgba);
delete[] buf;
}
我们要保存一个图片也可以从内存中直接读取后保存,假定我们熟悉使用opencv也是非常方便,不过,在程序中显然不能为了一个png等图片引入opencv,要看功能而定。