读写使用一个头文件,可以不使用libpng,libjpeg等等库,好处是更为简单,使用opengl时极其简单。
定义STB_IMAGE_IMPLEMENTATION,预处理器会修改头文件,让其只包含相关的函数定义源码,将这个头文件包含源代码
#include写文件#define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" int main(int argc, const char * argv[]) { int width, height, nrChannels; unsigned char *data = stbi_load("test.jpg", &width, &height, &nrChannels, 0); printf("w %d, h %d, c %dn", width, height, nrChannels); return 0; }
注意时rgba的写入,四字节
#include#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; //rgba unsigned char *data = stbi_load("test.png", &w, &h, &n, 0); printf("%d, %d, %dn", w, h, n); //rgba for (int dx = 0; dx < 10; ++dx) { data[n * w * 10 + dx * n + 0] = 255; data[n * w * 10 + dx * n + 1] = 255; data[n * w * 10 + dx * n + 2] = 128; data[n * w * 10 + dx * n + 3] = 100; } //write image stbi_write_png("write.png", w, h, n, data, w * n); stbi_image_free(data); return 0; }



