Skip to content

Instantly share code, notes, and snippets.

@maple-nishiyama
Last active August 29, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maple-nishiyama/267e1ca840eebc968e3d to your computer and use it in GitHub Desktop.
Save maple-nishiyama/267e1ca840eebc968e3d to your computer and use it in GitHub Desktop.
Rustで画素のバイト列をPPMフォーマットでファイルに書き出す
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();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment