c++ - c++ 中的硬编码位图会产生倾斜的线条

标签 c++ image bitmap

我试图找出如何在通过 C++ 生成的硬编码位图文件中绘制垂直直线:

#include <fstream>
using std::ifstream;
using std::ofstream;
#include <iostream>
using std::cout;
using std::endl;



int main ()
{
   ifstream infile ("white8x8.bmp");
   ofstream outfile ("output.bmp");
   char c;
   cout << "Start of original read/write: " << endl;
   for (int i = 0; i <= 53; i++)
   {
      infile.read (&c, 1);
      cout << (int) c << ' ' << c;
      outfile.write (&c, 1);
   }
   char z = 0;
   char x = 0;
   int j_prev = 0;
   for (int i = 0; i <= 250; i++){
      for (int j = 0; j <= 250; j++)
      {

         if(j == 10){
           c = 0;
           z = 0;
           x = 0;
           outfile.write (&c, 1);
           outfile.write (&x, 1);
           outfile.write (&z, 1);
           j_prev = j;
         }
         /*if(j %250 == 0){
           c = 0;
           z = 0;
           x = 0;
           outfile.write (&c, 1);
           outfile.write (&x, 1);
           outfile.write (&z, 1);
         }*/
         else{
           c = 255;
           x = 255;
           z = 255;
           outfile.write (&c, 1);
           outfile.write (&x, 1);
           outfile.write (&z, 1);
         }
      }
   }

   cout << endl << "Start of read new file: " << endl;
   infile.close();
   outfile.close();
   ifstream out2 ("output.bmp");
   out2.seekg(53);
   int count = 0;
   for(int i = 53; i < 15000; i++){

     out2.read(&c, 1);
     cout << count << ":" << (int) c << ' ' << c;
     count++;
   }
   out2.close();
   return 0;
}

我认为您可以将像素阵列视为一个二维阵列,而获得一条水平线只需要在每次 j 达到特定数字时绘制一个像素。情况似乎并非如此,因为这样做会给我一条斜线,如下所示。

output.jpg

为了澄清起见,我从一个已经创建的位图中复制位图 header 信息,然后简单地创建一个伴随的像素数组并从那里修改它。

最佳答案

BMP 文件要求每行填充为 4 字节的倍数。你的行数是 250*3=750,不是4 的倍数;在每行的开头填充 2 个字节,导致它被偏移。只需在 j 循环的末尾写入额外的 2 个字节的零即可。

关于c++ - c++ 中的硬编码位图会产生倾斜的线条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42103191/

相关文章:

C++ 抽象一个模板化类型,保留 T(虚拟)

c++ - 使用 OpenMP 的 x86 上的原子最小值

php - 如何处理向服务器请求很多动态图片?

android - 找不到应用程序文件夹

android - 自定义 View 转换为位图返回黑色图像

c++ - Makefile:对 'std::...' 的 undefined reference

c++ - 堆栈或堆上的成员值?

javascript - 通过选择带有 Id 的图像来更改带有 Id 的文本

c# - 生成低位深度的图像文件?

java - 位图跟随我的手指出现问题