2.Output an Image
This commit is contained in:
commit
ae2f086637
|
@ -0,0 +1 @@
|
||||||
|
/target
|
|
@ -0,0 +1,7 @@
|
||||||
|
# This file is automatically @generated by Cargo.
|
||||||
|
# It is not intended for manual editing.
|
||||||
|
version = 4
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "ray-trace-w1"
|
||||||
|
version = "0.1.0"
|
|
@ -0,0 +1,6 @@
|
||||||
|
[package]
|
||||||
|
name = "ray-trace-w1"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2024"
|
||||||
|
|
||||||
|
[dependencies]
|
|
@ -0,0 +1,36 @@
|
||||||
|
/*
|
||||||
|
* -------width(i)-------
|
||||||
|
* |
|
||||||
|
* |
|
||||||
|
* height(j)
|
||||||
|
* |
|
||||||
|
* |
|
||||||
|
* ----------------------
|
||||||
|
*
|
||||||
|
* ppm p3 format:
|
||||||
|
*
|
||||||
|
* P3
|
||||||
|
*
|
||||||
|
* [width] [height]
|
||||||
|
* [max color]
|
||||||
|
* R1 G1 B1
|
||||||
|
* R2 G2 B2
|
||||||
|
* R3 G3 B3
|
||||||
|
* ...xN
|
||||||
|
*/
|
||||||
|
pub fn gen_gradient_ppm_p3(width: i32, height: i32) -> String {
|
||||||
|
let mut img_content = format!("P3\n{} {}\n255\n", width, height);
|
||||||
|
|
||||||
|
for j in 0..height {
|
||||||
|
for i in 0..width {
|
||||||
|
let r = 256.0 * (i as f32 / (width-1) as f32);
|
||||||
|
let g = 256.0 * (j as f32 / (height-1) as f32);
|
||||||
|
let b = 256.0 * ((i+j) as f32 / (width + height - 2) as f32);
|
||||||
|
|
||||||
|
img_content.push_str(format!("{} {} {}", r as u8, g as u8, b as u8).as_str());
|
||||||
|
img_content.push('\n');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
img_content
|
||||||
|
}
|
|
@ -0,0 +1,10 @@
|
||||||
|
use write_file_util::{write_image};
|
||||||
|
use image::{gen_gradient_ppm_p3};
|
||||||
|
|
||||||
|
mod image;
|
||||||
|
mod write_file_util;
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
let ppm_content = gen_gradient_ppm_p3(400, 225);
|
||||||
|
write_image(ppm_content, "./target/test.ppm".to_string())
|
||||||
|
}
|
|
@ -0,0 +1,12 @@
|
||||||
|
use std::{fs::File, io::{BufWriter, Write}};
|
||||||
|
|
||||||
|
pub fn write_image(content: String, file_path: String) {
|
||||||
|
if let Ok(file) = File::create(file_path) {
|
||||||
|
let mut writer = BufWriter::new(file);
|
||||||
|
if let Err(e) = writer.write(content.as_bytes()) {
|
||||||
|
println!("写出失败:{:#}", e)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
println!("PPM保存失败")
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue