Skip to main content

reading_and_writing_rasters/
reading_and_writing_rasters.rs

1use anyhow::Result;
2use tempfile::NamedTempFile;
3use std::path::PathBuf;
4use ndarray::{Array2, array};
5use hydro_analysis::{rasterfile_to_array, array_to_rasterfile};
6
7fn main() -> Result<()> {
8    let d8: Array2<u8> = array![
9        [0, 3, 3, 7],
10        [1, 4, 9, 2],
11        [5, 6, 8, 0],
12    ];
13    let nd: u8 = 255;
14    let crs: u16 = 2193;
15    let geo: [f64;6] = [1361171.0, 8.0, 0.0, 5006315.0, 0.0, -8.0];
16    let gdir  = [1u64, 1, 0, 7, 1024, 0, 1, 1, 1025, 0, 1, 1, 1026, 34737, 48, 0, 2049, 34737, 9, 48, 2054, 0, 1, 9102, 3072, 0, 1, 2193, 3076, 0, 1, 9001];
17    let proj: &str = "NZGD2000 / New Zealand Transverse Mercator 2000|NZGD2000|";
18    let tmp = NamedTempFile::new()?;
19    let ofn: PathBuf = tmp.path().to_path_buf();
20    println!("Writing array to {:?}", ofn);
21    array_to_rasterfile::<u8>(&d8, nd, &geo, &gdir, &proj, &ofn)?;
22
23    // read file back in
24    println!("Reading {:?} into new array and checking got same values", ofn);
25    let (d8_new, nd_new, crs_new, geo_new, gdir_new, proj_new) = rasterfile_to_array::<u8>(&ofn)?;
26
27    // checking got same values back
28    assert_eq!(d8_new.shape(), d8.shape());
29    assert_eq!(d8_new, d8);
30
31    assert_eq!(nd_new, nd);
32    assert_eq!(crs_new, crs);
33    assert_eq!(geo_new, geo);
34    assert_eq!(gdir_new, gdir);
35    assert_eq!(proj_new, proj);
36
37    tmp.close()?;
38
39    Ok(())
40}