将书上对应的代码抄写了一遍。
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int nx = 200;
int ny = 100;
ofstream outfile( "mytest.txt", ios_base::out);
outfile << "P3\n" << nx << " " << ny << "\n255\n";
std::cout << "P3\n" << nx << " " << ny << "\n255\n";
for (int j = ny-1; j >= 0; j--)
{
for (int i = 0; i < nx; i++)
{
float r = float(i) / float(nx);
float g = float(j) / float(ny);
float b = 0.2;
int ir = int (255.99*r);
int ig = int (255.99*g);
int ib = int (255.99*b);
outfile << ir << " " << ig << " " << ib << "\n";
std::cout << ir << " " << ig << " " << ib << "\n";
}
}
}
将代码原封不动的输入后,确实能够运行(给作者点个赞)。但是说好的图片呢?原文有这么一句话:Opening the output file (in ToyViewer on my mac, but try it in your favorite viewer and google “ppm viewer” if your viewer doesn’t support it) shows(结果的那张图)。
有两个疑问:
1. “the output file”在哪?
2. “ppm viewer”是什么?
感觉告诉我接下来应该这么做:先将输出结果导入文件(即输出到文件),然后用一个ppm viewer来将这个图片看成图片(但愿如此)。
2.1 将结果输出到文件
如上红色部分的代码就是为了将输出结果导入文件。
#include <fstream>
ofstream outfile( "mytest.txt", ios_base::out);
outfile << "P3\n" << nx << " " << ny << "\n255\n";
outfile << ir << " " << ig << " " << ib << "\n";
简单解释如下:
#include <fstream>
/*iostream是输入输出流库标准文件(注意它没有后缀),它包含cout的信息,这对我们的程序是必需的。#include是预处理器指示符(preprocessor directive),它把iostream的内容读入我们的文本文件中*/
ofstream outfile( ".\\results\\FirstImage.txt", ios_base::out);
/*打开当前目录(工程目录)下results文件夹中的FirstImage.txt文件*/
outfile << "P3\n" << nx << " " << ny << "\n255\n";
/*往文件中写入数据*/
顺便说一下标准输出:
#include <iostream>
using namespace std;
/*这条语句被称作using指示符(using directive)。 C++标准库中的名字都是在一个称作std的名字空间中声明的,这些名字在我们的程序文本文件中是不可见的,除非我们显式地使它们可见。using指示符告诉编译器要使用在名字空间std中声明的名字。*/
std::cout << "P3\n" << nx << " " << ny << "\n255\n";
/*往屏幕上输出数据*/
将结果输出到文件mytest.txt,这个就是“the output file”啦。
(这个文件已经传到“我的资源”中)
2.2 找一个ppm viewer
结缘巧合,找到了XnView。用这个软件看mytest.txt时,看到的是这个:这里贴出一张通过“XnView”将结果的.txt转换成.jpg后的图片:
完整的操作步骤是这样的滴: