2017-02-08 53 views
1

林试图找出如何通过C++生成一个硬编码的位图文件绘制直线的垂直线:硬编码位在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

只是为了澄清我从一个已经创建的位图复制位图的头信息,然后简单地制造配套的像素阵列,并从那里修改它。

+0

BMP必须填充到4个像素的倍数。 http://stackoverflow.com/questions/29440672/bmp-file-line-padding-issue –

+0

如果你的图像的宽度不能被4(或8)整除,那么从我记忆中,你必须做到这一点所以,否则你会得到楼梯效果。 – PaulMcKenzie

+2

@RetiredNinja 4个字节,而不是4个像素。 –

回答

3

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

+0

也许我误解了你,但在else支架的右括号后面插入2个零字节后,我最终得到了一个在整个图像中颜色偏斜的bmp? – goetztyler

+0

@goetztyler对不起,我不清楚。当我说“最后”时,我真的意思是*结束后*。 –