Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Needs these dependencies in Cargo.toml
- png = "0.17.5"
- num = "0.4.0"
- */
- use std::path::Path;
- use std::fs::File;
- use std::io::BufWriter;
- use num::pow::Pow;
- pub fn main()
- {
- let path = Path::new(r"/home/thorsten/Temp/image.png");
- let width = 512;
- let height = 512;
- let max_iterations: u16 = 64;
- let start_x = -1.5;
- let start_y = -1.0;
- let scale = 2.0;
- let max_value = ((max_iterations - 1) * (256 / max_iterations)) as u8;
- let mut pixels: Vec<u8> = Vec::new();
- let delta_x: f64 = scale / width as f64;
- let delta_y: f64 = scale / height as f64;
- let mut current_x: f64;
- let mut current_y: f64 = start_y;
- for _ in 0..height
- {
- current_x = start_x;
- for _ in 0..width
- {
- let c = num::complex::Complex::new(current_x, current_y);
- let mut z = c.clone();
- let mut iterations: u16 = 0;
- for i in 0..max_iterations
- {
- z = z.pow(2.0) + c;
- if z.clone().to_polar().0 >= 2.0
- {
- break;
- }
- iterations = i;
- }
- let mut p_val = (iterations * (256 / max_iterations)) as u8;
- if p_val == max_value
- {
- p_val = 0;
- }
- pixels.push(p_val);
- pixels.push(p_val);
- pixels.push(p_val);
- pixels.push(255);
- current_x += delta_x;
- }
- current_y += delta_y;
- }
- save_png(width, height, &pixels, path);
- }
- fn save_png(width: u32, height: u32, pixels: &Vec<u8>, path: &Path)
- {
- assert!(width > 0);
- assert!(height > 0);
- assert_eq!((width * height) as usize, pixels.len() / 4);
- let file = File::create(path).unwrap();
- let ref mut w = BufWriter::new(file);
- let mut encoder = png::Encoder::new(w, width, height); // Width is 2 pixels and height is 1.
- encoder.set_color(png::ColorType::Rgba);
- encoder.set_depth(png::BitDepth::Eight);
- encoder.set_trns(vec!(0xFFu8, 0xFFu8, 0xFFu8, 0xFFu8));
- encoder.set_source_gamma(png::ScaledFloat::from_scaled(45455)); // 1.0 / 2.2, scaled by 100000
- encoder.set_source_gamma(png::ScaledFloat::new(1.0 / 2.2)); // 1.0 / 2.2, unscaled, but rounded
- let source_chromaticities = png::SourceChromaticities::new( // Using unscaled instantiation here
- (0.31270, 0.32900),
- (0.64000, 0.33000),
- (0.30000, 0.60000),
- (0.15000, 0.06000),
- );
- encoder.set_source_chromaticities(source_chromaticities);
- let mut writer = encoder.write_header().unwrap();
- writer.write_image_data(&pixels).unwrap(); // Save
- }
RAW Paste Data
Copied