限制條件
- 最終部署於嵌入式裝置(無作業系統或 RTOS),**不能依賴 OpenCV、Qt、VS ATL/MFC/GDI+** 等重型庫。
- 需單一
.h 或 .h/.c 組合,輕鬆整合進現有工程。
- 功能:讀取圖片(BMP/PNG/JPG)、存取像素、基本縮放/旋轉/灰階。
推薦庫
| 庫 | 特點 | 授權 |
| stb_image / stb_image_write / stb_image_resize | Sean Barrett 單頭檔,支援 PNG/JPG/BMP/TGA 讀寫、縮放,極輕量,廣泛用於遊戲/嵌入式 | Public Domain / MIT |
| lodepng | 單 .h/.c,純 C++ 實現 PNG 編解碼,無依賴 | Zlib |
| nanojpg | 極小 JPEG 解碼器,適合極受限 MCU | Public Domain |
| TinyEXIF | 讀取 JPEG EXIF 方向標籤,配合旋轉校正 | MIT |
整合範例
// 僅需複製 stb_image.h, stb_image_write.h, stb_image_resize.h 到專案
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"
int w, h, ch;
unsigned char* data = stbi_load("test.jpg", &w, &h, &ch, 0); // ch=3(RGB)或4(RGBA)
if (data) {
// 存取像素:data[y * w * ch + x * ch + c]
// 灰階轉換、縮放等自行實現或用 stb_image_resize
stbi_write_png("out.png", w, h, ch, data, w * ch);
stbi_image_free(data);
}
避坑指南
- 嵌入式編譯器需支援 C99/C++11(
stdint.h, inline 等)。
- 大圖解碼需足夠堆/棧空間,考慮**串流式解碼**或分塊處理。
- 交叉編譯工具鏈需正確連結標準數學庫 (
-lm)。