Advertisement
Guest User

Untitled

a guest
Jun 29th, 2015
212
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.67 KB | None | 0 0
  1. use std::fs::OpenOptions;
  2. use std::path::Path;
  3. use std::io::BufWriter;
  4. use std::io::Write;
  5.  
  6.  
  7. // 画素
  8. struct PIXEL {
  9. r: u8,
  10. g: u8,
  11. b: u8,
  12. }
  13.  
  14. const WIDTH: usize = 300;
  15. const HEIGHT: usize = 300;
  16. const SIZE: usize = WIDTH * HEIGHT * 3;
  17.  
  18. fn main() {
  19. let mut ppm = [0u8; SIZE];
  20. create_image(&mut ppm);
  21. write_ppm("test.ppm", WIDTH, HEIGHT, &ppm);
  22. }
  23.  
  24. // 市松模様
  25. fn create_image(buf: &mut [u8; SIZE]) {
  26. for x in 0..WIDTH {
  27. for y in 0..HEIGHT {
  28. if ((x / 30 % 2) + (y / 30 % 2)) % 2 == 1 {
  29. let px = PIXEL{r: 255, g: 255, b: 255};
  30. set_pixel(px, x, y, WIDTH, HEIGHT, buf);
  31. } else {
  32. let px = PIXEL{r: 0, g: 0, b: 0};
  33. set_pixel(px, x, y, WIDTH, HEIGHT, buf);
  34. }
  35. }
  36. }
  37. }
  38.  
  39. fn get_pixel(x: usize, y: usize, w: usize, h: usize, buf: &[u8; SIZE]) {
  40. let ind: usize = (y * h + x) * 3;
  41. PIXEL {r: buf[ind], g: buf[ind + 1], b: buf[ind + 2]};
  42. }
  43.  
  44. fn set_pixel(px: PIXEL, x: usize, y: usize, w: usize, h: usize, buf: &mut [u8; SIZE]) {
  45. let ind: usize = (y * h + x ) * 3;
  46. buf[ind] = px.r;
  47. buf[ind + 1] = px.g;
  48. buf[ind + 2] = px.b;
  49. }
  50.  
  51. // PPM フォーマットでファイルに書き出し
  52. fn write_ppm(filename: &str, width: usize, height: usize, bytes: &[u8]) {
  53. let path = Path::new(filename);
  54. let file = OpenOptions::new()
  55. .write(true)
  56. .create(true)
  57. .open(&path)
  58. .unwrap();
  59.  
  60. let mut writer = BufWriter::new(&file);
  61. writer.write_all(b"P6\n").unwrap();
  62. writer.write_all(format!("{} {}\n", width, height).as_bytes()).unwrap();
  63. writer.write_all(b"255\n").unwrap();
  64. writer.write_all(bytes).unwrap();
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement