繁体   English   中英

如何用C ++创建ascii正方形,三角形,矩形或圆形并将其保存到便携式位图文件中?

[英]How to create in ascii square, triangle, rectangle or circle with C++ and save it to portable bitmap file?

我不知道如何在第0行和第1行保存来创建一个数字。 这是我的代码,它生成带零的行。 我需要创建一个正方形或三角形,或矩形(无关紧要)。 只需要知道如何正确地做到这一点并保存为pbm(便携式位图)作为单色图像。

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
ofstream file;

int width=5;
int height=5;
int tab [10][10];

file.open("graphics.pbm");
if(file.good() == true)
{
    file << "P1" << endl;
    file << "# comment" << endl;
    file << "10 10" << endl;

    for (int  i=0; i<width; i++)
    {
        for (int j=0; j<height; j++)
        {
            tab[i][j]=0;
        }
    }

    for (int  i=0; i<width; i++)
    {
        for (int j=0; j<height; j++)
        {
            file << tab[i][j] << " ";
        }
    }

file.close();
}

return 0;
}

那么你有一些工作要做......你需要为每个几何形状指定一个函数来填充你的图像。

这里有一个更像C ++的例子,类Image处理计算几何形式的方法,例如makeFillCircle() Image类还处理PBM输出。 说明使用std::ostream operator<<保存它是多么容易!

#include <vector>
#include <iostream>
#include <algorithm>

struct Point { 
    Point(int xx, int yy) : x(xx), y(yy) {} 
    int x; 
    int y; 
};

struct Image {
    int width;
    int height;
    std::vector<int> data; // your 2D array of pixels in a linear/flatten storage

    Image(size_t w, size_t h) : width(w), height(h), data(w * h, 0) {} // we fill data with 0s

    void makeFillCircle(const Point& p, int radius) {
        // we do not have to test every points (using bounding box)
        for (int i = std::max(0, p.x - radius); i < std::min(width-1, p.x + radius) ; i ++) {
            for (int j = std::max(0,p.y - radius); j < std::min(height-1, p.y + radius); j ++) {
                // test if pixel (i,j) is inside the circle
                if ( (p.x - i) * (p.x - i) + (p.y - j) * (p.y - j) < radius * radius ) {
                    data[i * width + j] = 1;  //If yes set pixel on 1 !
                }
            }
        }
    }
};

std::ostream& operator<<(std::ostream& os, const Image& img) {
    os << "P1\n" << img.width << " " << img.height << "\n";
    for (auto el : img.data) { os << el << " "; }
    return os;
}

int main() {
    Image img(100,100);
    img.makeFillCircle(Point(60,40), 30); // first big circle
    img.makeFillCircle(Point(20,80), 10); // second big circle
    std::cout << img << std::endl; // the output is the PBM file
}

现场代码

结果是:

两个圆圈

并且瞧...我让你有兴趣创建自己的函数makeRectangle()makeTriangle()来满足你的需求! 这需要一些小数学!

编辑奖金

正如评论中所要求的,这里有一个小成员函数,可以将图像保存在文件中。 将它添加到Image类中(如果您喜欢在类外部使用自由函数,也可以添加它)。 由于我们有一个ostream运算符<<这很简单:

void save(const std::string& filename) {
    std::ofstream ofs;
    ofs.open(filename, std::ios::out);
    ofs << (*this);
    ofs.close();
}

另一种不修改代码的方法是在终端上用类似的东西捕获程序的输出:

./main >> file.pgm

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM