C++输出bmp图片的宽和高
时间: 2024-10-22 08:15:44 浏览: 8
C++实现读取图片长度和宽度
在C++中,读取BMP图像文件的宽度和高度通常需要借助第三方库,因为标准库本身并不提供直接解析BMP的能力。libbmp、FreeImage库等都是常见的用于处理位图文件的选择。下面是一个简单的示例,使用FreeImage库来获取BMP图片的尺寸:
```cpp
#include <freeimage.h>
bool isBmp(const char* filename) {
return FreeImage_GetExtension(filename) == ".bmp";
}
void getBMPDimensions(const char* filename, int& width, int& height) {
if (!isBmp(filename)) {
throw std::runtime_error("Not a BMP file.");
}
FIBITMAP* dib = FreeImage_Load(filename);
if (!dib) {
throw std::runtime_error("Failed to load the image.");
}
width = FreeImage_GetWidth(dib);
height = FreeImage_GetHeight(dib);
FreeImage_Unload(dib); // Don't forget to release the memory after use
}
int main() {
const char* bmpFile = "path_to_your_bmp_file.bmp";
int width, height;
try {
getBMPDimensions(bmpFile, width, height);
std::cout << "Width: " << width << ", Height: " << height << std::endl;
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
return 0;
}
```
阅读全文