You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何预先判断BMP文件的存储方向:正向还是倒置?

How to Determine the Storage Orientation (Top-Down vs. Bottom-Up) of a BMP File

Hey there! Great question—this is a common gotcha when working with BMP files, but luckily the answer is baked right into the file's header data. Let me break this down for you:

  • Check the Height field in the BITMAPINFOHEADER
    The core clue lives in the 4-byte signed integer at offset 20 (0x14) in the BMP file's info header. Here's what it means:

    • If the value is positive: The bitmap is stored bottom-up (the first pixel in the file is the bottom-left corner of the image). This is the standard/default for most BMPs.
    • If the value is negative: The bitmap is stored top-down (the first pixel is the top-left corner). This is less common but used in some cases (like certain Windows GDI operations).
  • Quick breakdown of the header structure
    To make sure you're reading the right field, here's the relevant part of the BITMAPINFOHEADER (in C-like terms for clarity):

    typedef struct tagBITMAPINFOHEADER {
        DWORD biSize;          // Size of this header (usually 40 bytes)
        LONG  biWidth;         // Width of the bitmap in pixels
        LONG  biHeight;        // Height (positive = bottom-up, negative = top-down)
        WORD  biPlanes;        // Must be 1
        WORD  biBitCount;      // Bits per pixel (1, 4, 8, 16, 24, 32)
        DWORD biCompression;   // Compression type (0 = BI_RGB, uncompressed)
        DWORD biSizeImage;     // Size of image data (can be 0 for BI_RGB)
        LONG  biXPelsPerMeter; // Horizontal resolution
        LONG  biYPelsPerMeter; // Vertical resolution
        DWORD biClrUsed;       // Number of colors used (0 = all)
        DWORD biClrImportant;  // Important colors (0 = all)
    } BITMAPINFOHEADER;
    

    Just remember to first skip the 14-byte BITMAPFILEHEADER before accessing this info header. The BITMAPFILEHEADER has the bfOffBits field which tells you where the pixel data starts, but for orientation checks, you only need to focus on the biHeight value's sign.

  • Edge cases to keep in mind

    • While rare, some older or non-standard BMPs might flout this convention—but 99% of the time, the biHeight sign is a reliable indicator.
    • If you're working with compressed BMPs (like BI_RLE8 or BI_RLE4), the bottom-up/top-down rule still applies to how the compressed pixel data is organized.

Once you read that biHeight value, you can immediately pick the correct processing scheme without having to test both options!

内容的提问来源于stack exchange,提问作者Moaz Naseem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:03:03