gpt4 book ai didi

c++ - 使用 BMP - 加载和保存

转载 作者:行者123 更新时间:2023-11-30 05:35:57 25 4
gpt4 key购买 nike

我们正在与 friend 一起尝试编写应用程序来处理 BMP 文件,我们将使其尽可能简单,因为我们才刚刚开始学习 C 和 C++。使用新的实际尺寸的线条复制效果很好,但现在我想添加灰度效果并遇到另一个问题:图片的右侧移动到左侧 - 检查图片。是什么导致了这个问题?

#include <iostream>
#include <fstream>
#include <stdio.h>
#include <unistd.h>


using namespace std;

void ReadBMP()
{
FILE* f = fopen("test2.bmp", "rb");
FILE* w = fopen("zapis.bmp", "wb");

if(f == NULL)
throw "Argument Exception";

unsigned char info[54];
fread(info, sizeof(unsigned char), 54, f);
fwrite(info, sizeof(unsigned char), 54, w);

int width = *(int*)&info[18];
int height = *(int*)&info[22];

cout << endl;
cout << "Width: " << width << endl;
cout << "Height: " << height << endl;



int realwidth = 3*width+(4 - ((3*width)%4))%4;
int volume = height * realwidth;
unsigned char* data = new unsigned char[volume];

fwrite(info, sizeof(unsigned char), 54, w);

fread(data, sizeof(unsigned char), volume, f);
unsigned char color = 0;

for(int i = 0; i < volume; i+=3)
{
color = 0;
color+=data[i]*0.114;
color+=data[i+1]*0.587;
color+=data[i+2]*0.299;
data[i] = color;
data[i+1] = color;
data[i+2] = color;
}


fwrite(data, sizeof(unsigned char), volume, w);



fclose(f);
fclose(w);
delete(data);
}

int main()
{
ReadBMP();
return 0;
}

Input image

Output image

最佳答案

您的图像数据大小公式有误。首先,您需要找到间距,方法是将宽度乘以每个像素的字节数(24 位图像为 3),然后四舍五入到最接近的 4 的倍数。然后将间距乘以高度;

int byte_width = width * 3;
int pitch = byte_width + (4 - byte_width % 4) % 4;
int volume = pitch * height;

关于c++ - 使用 BMP - 加载和保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33682098/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com