简单易用的C/C++ 图像库 stb_image stb_image_write
stb_image & stb_image_write庫 簡單介紹
Github: https://github.com/nothings/stb/
stb_image
stb的庫像素數(shù)據(jù)都是從左到右,從上到下存儲
使用 stbi_set_flip_vertically_on_load(true); 上下翻轉(zhuǎn)
使用 stbi_flip_vertically_on_write(true); 在寫數(shù)據(jù)的時候翻轉(zhuǎn) (在stb_write_image中)
- 使用庫
#include <...> #define STB_IMAGE_IMPLEMENTATION // include之前必須定義 #include "stb_image.h"- 局限
- no 12-bit-per-channel JPEG
- no JPEGs with arithmetic coding
- GIF always returns *comp=4
- 基礎(chǔ)用法
int x,y,n; unsigned char *data = stbi_load("filename",&x,&y,&n,0); // filename : 文件名 // x : 圖片寬 // y : 圖片高 // n : 顏色通道個數(shù) // 最后一個為自己設(shè)置的顏色通道個數(shù),如果非0就按照此數(shù)值讀取圖像 // 返回值非NULL說明導(dǎo)入成功 // Do Something stbi_image_free(data);顏色通道
- 1: 灰度圖
- 2: 灰度Alpha圖
- 3: 紅綠藍三色圖
- 4: 紅綠藍三色Alpha圖
錯誤信息
const char* stbi_failure_reason()返回錯誤信息字符串
- 定義 STBI_NO_FAILURE_STRINGS 避免編譯這些字符串
- 定義 STBI_FAILURE_USERMSG 使錯誤信息更加容易閱讀
Unicode
Windows環(huán)境下可能需要滿足Unicode的文件名
#define STBI_WINDOWS_UTF8可以使文件名滿足Unicode
也可以使用stbiw_convert_wchar_to_utf8將Windows wchar_t 轉(zhuǎn)換為 utf8.
Addition
- 預(yù)編譯取消對某個格式的解析 :#define STBI_NO_PNG…
- 預(yù)編譯限制只能某個格式解析 :#define STBI_ONLY_PNG…
Else
獲取x,y位置的像素信息,data為圖像指針,n為顏色通道數(shù)
data[w*n*x+n*y+i] (i = 0,1,…,n-1)
作者還介紹了 SIMD支持, HDR圖像支持, Iphone PNG支持
stb_image_write
- 使用庫
#include <...> #define STB_IMAGE_WRITE_IMPLEMENTATION // include之前必須定義 #include "stb_image_write.h"- 簡單的使用
int stbi_write_png(char const *filename, int w, int h, int comp, const void *data, int stride_in_bytes);int stbi_write_bmp(char const *filename, int w, int h, int comp, const void *data);int stbi_write_tga(char const *filename, int w, int h, int comp, const void *data);int stbi_write_jpg(char const *filename, int w, int h, int comp, const void *data, int quality);int stbi_write_hdr(char const *filename, int w, int h, int comp, const float *data);- Else
作者還提到了PNG壓縮,可提供自己的壓縮函數(shù),還有JPG質(zhì)量的參數(shù)
代碼示例
#include <iostream> #include <stdlib.h>#define STB_IMAGE_IMPLEMENTATION #include <stb_image.h>#define STB_IMAGE_WRITE_IMPLEMENTATION #include <stb_image_write.h>using namespace std;void setAlpha(int x, int y, int n, int w, int alpha, unsigned char *data) {data[w*n*x + y * n + n - 1] = alpha; }int main() {const char *filepath = "demo.png";int w, h, n;unsigned char *data = stbi_load(filepath, &w, &h, &n, 0);if (data == NULL) {cout << "ERROE_FILE_NOT_LOAD" << endl;return -1;}else {cout << w << " " << h << " " << n << endl;// 將上半身設(shè)置為透明for (int i = 0; i < h / 2; i++) {for (int j = 0; j < w; j++) {setAlpha(i, j, n, w, 0, data);}}// 寫的時候翻轉(zhuǎn)stbi_flip_vertically_on_write(true);stbi_write_png("out.png", w, h, n, data, 0);}stbi_image_free(data);return 0; }- 原圖像
- 處理后
作者還有一個stb_image_resize.h支持對圖像的簡單放縮平移等操作
總結(jié)
以上是生活随笔為你收集整理的简单易用的C/C++ 图像库 stb_image stb_image_write的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: matlab图片快速傅里叶变换,图像傅里
- 下一篇: 如何实现文档协作共享?