簡單易用的C/C++ 圖像庫 stb_image & stb_image_write

stb_image & stb_image_write庫 簡單介紹

Github: https://github.com/nothings/stb/

stb_image

stb的庫像素數據都是從左到右,從上到下存儲

使用 stbi_set_flip_vertically_on_load(true); 上下翻轉

使用 stbi_flip_vertically_on_write(true); 在寫數據的時候翻轉 (在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

- 基礎用法

int x,y,n;
unsigned char *data = stbi_load("filename",&x,&y,&n,0);
// filename : 文件名
// x : 圖片寬 
// y : 圖片高
// n : 顏色通道個數
// 最後一個爲自己設置的顏色通道個數,如果非0就按照此數值讀取圖像
// 返回值非NULL說明導入成功
// 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環境下可能需要滿足Unicode的文件名

#define STBI_WINDOWS_UTF8可以使文件名滿足Unicode

也可以使用stbiw_convert_wchar_to_utf8Windows wchar_t 轉換爲 utf8.

Addition

  • 預編譯取消對某個格式的解析 :#define STBI_NO_PNG…
  • 預編譯限制只能某個格式解析 :#define STBI_ONLY_PNG…

Else

獲取x,y位置的像素信息,data爲圖像指針,n爲顏色通道數

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壓縮,可提供自己的壓縮函數,還有JPG質量的參數

代碼示例

#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;
		// 將上半身設置爲透明
		for (int i = 0; i < h / 2; i++) {
			for (int j = 0; j < w; j++) {
				setAlpha(i, j, n, w, 0, data);
			}
		}
		// 寫的時候翻轉
		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支持對圖像的簡單放縮平移等操作

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章