Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::fs::OpenOptions;
- use std::path::Path;
- use std::io::BufWriter;
- use std::io::Write;
- // 画素
- struct PIXEL {
- r: u8,
- g: u8,
- b: u8,
- }
- const WIDTH: usize = 300;
- const HEIGHT: usize = 300;
- const SIZE: usize = WIDTH * HEIGHT * 3;
- fn main() {
- let mut ppm = [0u8; SIZE];
- create_image(&mut ppm);
- write_ppm("test.ppm", WIDTH, HEIGHT, &ppm);
- }
- // 市松模様
- fn create_image(buf: &mut [u8; SIZE]) {
- for x in 0..WIDTH {
- for y in 0..HEIGHT {
- if ((x / 30 % 2) + (y / 30 % 2)) % 2 == 1 {
- let px = PIXEL{r: 255, g: 255, b: 255};
- set_pixel(px, x, y, WIDTH, HEIGHT, buf);
- } else {
- let px = PIXEL{r: 0, g: 0, b: 0};
- set_pixel(px, x, y, WIDTH, HEIGHT, buf);
- }
- }
- }
- }
- fn get_pixel(x: usize, y: usize, w: usize, h: usize, buf: &[u8; SIZE]) {
- let ind: usize = (y * h + x) * 3;
- PIXEL {r: buf[ind], g: buf[ind + 1], b: buf[ind + 2]};
- }
- fn set_pixel(px: PIXEL, x: usize, y: usize, w: usize, h: usize, buf: &mut [u8; SIZE]) {
- let ind: usize = (y * h + x ) * 3;
- buf[ind] = px.r;
- buf[ind + 1] = px.g;
- buf[ind + 2] = px.b;
- }
- // PPM フォーマットでファイルに書き出し
- fn write_ppm(filename: &str, width: usize, height: usize, bytes: &[u8]) {
- let path = Path::new(filename);
- let file = OpenOptions::new()
- .write(true)
- .create(true)
- .open(&path)
- .unwrap();
- let mut writer = BufWriter::new(&file);
- writer.write_all(b"P6\n").unwrap();
- writer.write_all(format!("{} {}\n", width, height).as_bytes()).unwrap();
- writer.write_all(b"255\n").unwrap();
- writer.write_all(bytes).unwrap();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement