Skip to main content

array_to_rasterfile

Function array_to_rasterfile 

Source
pub fn array_to_rasterfile<T>(
    data: &Array2<T>,
    nd: T,
    geotrans: &[f64; 6],
    geokeydir: &[u64],
    proj: &str,
    outfile: &PathBuf,
) -> Result<(), RasterError>
where T: Pod + ToString,
Expand description

Writes a 2D array of values to a GeoTIFF raster with geo metadata.

§Type Parameters

  • T: The element type of the array, which must implement bytemuck::Pod (for safe byte casting) and ToString (for writing NoData values to metadata).

§Parameters

data: A 2D array (ndarray::Array2<T>) containing raster pixel values. nd: NoData value geotrans: A 6-element array defining the affine geotransform: [origin_x, pixel_size_x, rotation_x, origin_y, rotation_y, pixel_size_y]. geokeydir: &u64 the GeoKeyDirectoryTag (best got from reading a raster) proj: PROJ string (best got from reading a raster) outfile: The path to the output .tif file.

§Returns

Ok() or a RasterError

§Errors

  • Returns RasterError::UnsupportedType if T can’t be mapped to a TIFF format.
  • Propagates I/O and TIFF writing errors

§Example

See examples/reading_and_writing_rasters.rs

Examples found in repository?
examples/reading_and_writing_rasters.rs (line 21)
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}