获取bmp图片宽高的最简代码(C)

写web后端的时候,有个需求是判断用户上传的bmp图片宽高,不能超出限制。
找了一堆代码,发现虽然功能很全,信息都有解析出来,但是略复杂了,于是仔细研究了下bmp图片格式,做了简化。

先直接上代码, 就8行,应该算是目前最简的了。如果有其他更简略的,欢迎交流

  #include <fstream>
  // get bmp picture width and height and skip other header information
  FILE *picture_file = fopen(BMP_FILE_PATH, "rb");
  int32_t bmp_width;
  int32_t bmp_height;
  int offset = sizeof(uint16_t) * 3 + sizeof(uint32_t) * 3;
  fseek(picture_file, offset, SEEK_SET);
  fread(&bmp_width, 1, sizeof(bmp_width), picture_file);
  fread(&bmp_height, 1, sizeof(bmp_height), picture_file);
  fclose(picture_file);
  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在 C 语言中显示 BMP 图片,你可以使用如下步骤: 1. 打开 BMP 文件并读取 BMP 文件头,获取图片宽度高度、每个像素占用的字节数等信息。 2. 读取 BMP 文件中的像素数据,将其存储在一个缓冲区中。 3. 使用图形库(如 SDL、OpenGL)将像素数据渲染到屏幕上。 以下是一个简单的示例代码,使用 SDL2 图形库来读取和显示 BMP 图片: ``` #include <stdio.h> #include <stdlib.h> #include <SDL2/SDL.h> #define SCREEN_WIDTH 640 #define SCREEN_HEIGHT 480 int main(int argc, char** argv) { SDL_Window* window = NULL; SDL_Surface* surface = NULL; SDL_Surface* image = NULL; SDL_Event event; // Initialize SDL if (SDL_Init(SDL_INIT_VIDEO) < 0) { printf("SDL could not initialize! SDL_Error: %s\n", SDL_GetError()); exit(1); } // Create window window = SDL_CreateWindow("BMP Viewer", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); if (window == NULL) { printf("Window could not be created! SDL_Error: %s\n", SDL_GetError()); exit(1); } // Load BMP image image = SDL_LoadBMP("image.bmp"); if (image == NULL) { printf("Unable to load image %s! SDL_Error: %s\n", "image.bmp", SDL_GetError()); exit(1); } // Set image position SDL_Rect image_rect; image_rect.x = (SCREEN_WIDTH - image->w) / 2; image_rect.y = (SCREEN_HEIGHT - image->h) / 2; // Get screen surface surface = SDL_GetWindowSurface(window); // Fill surface with white color SDL_FillRect(surface, NULL, SDL_MapRGB(surface->format, 255, 255, 255)); // Blit image to surface SDL_BlitSurface(image, NULL, surface, &image_rect); // Update screen SDL_UpdateWindowSurface(window); // Wait for user to quit while (1) { if (SDL_PollEvent(&event) && event.type == SDL_QUIT) { break; } } // Free resources and quit SDL SDL_FreeSurface(image); SDL_DestroyWindow(window); SDL_Quit(); return 0; } ``` 在这个示例代码中,我们使用了 SDL2 图形库来创建窗口,加载 BMP 图片,渲染像素数据,并等待用户关闭窗口。你可以将上面的示例代码复制到你的本地环境中运行并查看效果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值