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

使用stbi_write_bmp保存白色图像出现黑列的原因排查

问题:生成全白BMP图像出现隔列变黑异常

以下代码意图生成1440×1080的全白色单通道BMP图像,但输出图像出现每隔一列变黑的异常:

#include "stb_image/stb_image.h"
#include "stb_image/stb_image_write.h"

int main(void){
    int width = 1440;
    int height = 1080;
    int j, l;
    float *img_slopes = (float *)malloc(width * height * sizeof(float));
    for (l = 0; l < width; l++) {
        for (j = 0; j < height; j++) {
            *(img_slopes + j * width + l) = 255;
        }
    }
    stbi_write_bmp("answer_blank.bmp", width, height, 1, img_slopes);
}

异常原因与问题解析

核心问题是数据类型不匹配,违背了stbi_write_bmp的参数要求:

  • stbi_write_bmp的第5个参数要求传入单字节无符号整数(uint8_t/unsigned char)类型的像素数据指针——单通道BMP的每个像素仅占1字节,取值范围为0-255。
  • 代码中使用float类型数组存储像素值,而float在多数系统中占4字节。当float*被传入函数时,函数会错误地将每个float的4个字节拆解为4个独立像素解析。
  • 给float赋值255时,其对应的二进制内存布局为0x437F0000,函数按单字节读取会依次得到0x00(黑色)、0x00(黑色)、0x7F(灰色)、0x43(深灰色)。结合图像宽度1440,这种4字节转4像素的错误解析会导致行数据错位,最终呈现隔列变黑的视觉异常。

修复方案

将像素数据类型改为uint8_t(或unsigned char),匹配BMP单通道的字节要求:

#include "stb_image/stb_image.h"
#include "stb_image/stb_image_write.h"
#include <stdint.h>
#include <stdlib.h>

int main(void){
    int width = 1440;
    int height = 1080;
    int j, l;
    // 用单字节类型分配内存,每个像素对应1字节
    uint8_t *img_data = (uint8_t *)malloc(width * height * sizeof(uint8_t));
    for (l = 0; l < width; l++) {
        for (j = 0; j < height; j++) {
            img_data[j * width + l] = 255;
        }
    }
    stbi_write_bmp("answer_blank.bmp", width, height, 1, img_data);
    free(img_data); // 释放内存,避免泄漏
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 06:33:22