我不知道如何在第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;
}
答案 0 :(得分:1)
你有一些工作要做......你需要为每个几何形状指定一个函数来填充你的图像。
这里有一个更像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
}
<强> Live Code 强>
结果是:
并且瞧...我为您提供了创建自己的功能makeRectangle()
,makeTriangle()
以满足您的需求!这需要一些小数学!
修改奖金
如评论中所述,这里有一个小成员函数,可以将图像保存在文件中。将它添加到Image类中(如果您喜欢在类外部使用自由函数,也可以添加它)。由于我们有一个ostream运算符&lt;&lt;这很简单:
void save(const std::string& filename) {
std::ofstream ofs;
ofs.open(filename, std::ios::out);
ofs << (*this);
ofs.close();
}
另一种不修改代码的方法是在终端上用类似的东西捕获程序的输出:
./main >> file.pgm