使用C++代码生成一张图片,需要用到PPM图像格式。 [
#include
#include
using namespace std;
int main()
{
ofstream outfile;
outfile.open(“IMG.txt”);
int nx = 800;
int ny = 400;
outfile << "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.2f;
int ir = int(255.99f \* r);
int ig = int(255.99f \* g);
int ib = int(255.99f \* b);
outfile << ir << " " << ig << " " << ib << "\\n";
}
}
outfile.close();
return 0;
}
最后生成一个txt文件,修改后缀为ppm: 用photoshop打开ppm文件,最后的效果图如下:
PPM参考链接:https://www.jianshu.com/p/e809269b4ad7 参考书籍:《Ray Tracing in One Weekend》 RTIOW系列项目地址:GitHub RTIOW系列笔记: RTIOW-ch1:Output an image RTIOW-ch2:The vec3 class RTIOW-ch3:Rays, a simple camera, and background RTIOW-ch4:Adding a sphere RTIOW-ch5:Surface normals and multiple objects RTIOW-ch6:Antialiasing RTIOW-ch7:Diffuse Materials RTIOW-ch8:Metal RTIOW-ch9:Dielectrics RTIOW-ch10:Positionable camera RTIOW-ch11:Defocus Blur RTIOW-ch12:Where next