Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Write a New Image

You have pixels in a Vec: a frame from a camera driver, or the output of your own stacking or calibration code. You want a FITS or XISF file that other programs open with the right metadata, and a WCS if you’ve solved the image. The crate has two ways to get there. AstroImage borrows your buffer and writes it with a builder. Image, the type Image::open returns, owns its pixels and suits a frame you’ll keep working on.

Write a buffer with AstroImage

Here a stacked, plate-solved frame goes to disk with its metadata and WCS:

use celestial_images::fits::header::keywords::Keyword;
use celestial_images::fits::io::reader::FitsFile;
use celestial_images::formats::astro_image::AstroImage;
use celestial_wcs::builder::WcsBuilder;
use celestial_wcs::spherical::Projection;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // A stacked frame from your own pipeline, already plate-solved
    let stack = vec![0.1f32; 1600 * 1200];
    let wcs = WcsBuilder::new()
        .crpix(800.5, 600.5)
        .crval(148.8882, 69.0653)
        .cd_matrix([[-3.2604e-4, 6.930e-5], [6.930e-5, 3.2604e-4]])
        .projection(Projection::tan())
        .build()?;

    AstroImage::new(&stack, [1600, 1200])
        .object("M81")
        .filter("L")
        .exposure(3600.0)
        .date_obs("2026-03-20T03:15:00")
        .keyword(Keyword::integer("NCOMBINE", 12).with_comment("frames stacked"))
        .wcs(&wcs)
        .write_to("m81_stack.fits")?;

    let mut fits = FitsFile::open("m81_stack.fits")?;
    for keyword in fits.get_header(0)?.keywords() {
        match &keyword.value {
            Some(value) => println!("{:<8} = {value}", keyword.name),
            None => println!("{} {}", keyword.name, keyword.comment.as_deref().unwrap_or("")),
        }
    }
    println!("checksums valid: {}", fits.validate_hdu_checksum(0)?.all_valid());
    Ok(())
}
SIMPLE   = T
BITPIX   = -32
NAXIS    = 2
NAXIS1   = 1600
NAXIS2   = 1200
EXTEND   = T
COMMENT FITS (Flexible Image Transport System) format is defined in 'Astronomy
COMMENT and Astrophysics', volume 376, page 359; bibcode: 2001A&A...376..359H
CTYPE1   = 'RA---TAN'
CTYPE2   = 'DEC--TAN'
CUNIT1   = 'deg'
CUNIT2   = 'deg'
CRPIX1   = 800.5
CRPIX2   = 600.5
CRVAL1   = 148.8882
CRVAL2   = 69.0653
CD1_1    = -0.00032604
CD1_2    = 6.93E-05
CD2_1    = 6.93E-05
CD2_2    = 0.00032604
LATPOLE  = 69.0653
OBJECT   = 'M81'
FILTER   = 'L'
EXPTIME  = 3600.0
DATE-OBS = '2026-03-20T03:15:00'
NCOMBINE = 12
DATASUM  = '847500'
CHECKSUM = '36gXA3ZV33dVA3ZV'
checksums valid: true

The mandatory cards (SIMPLE through EXTEND) come from the data, so you never set them. The WCS cards come from wcs.to_keywords(), which Building a WCS in Code describes, and a keyword you set with the same name as a WCS card replaces it. write_fits and write_to add DATASUM and CHECKSUM, so a reader can check that the file arrived intact. A compressed file gets them on the HDU that holds the compressed image.

The metadata setters write the keywords most capture and processing programs read:

SetterKeyword
objectOBJECT
telescopeTELESCOP
instrumentINSTRUME
observerOBSERVER
filterFILTER
exposureEXPTIME, seconds
temperatureCCD-TEMP, °C
gainGAIN
binningXBINNING and YBINNING
date_obsDATE-OBS

date_obs writes the string you pass and doesn’t check it. Use the FITS form, YYYY-MM-DDThh:mm:ss with optional fractional seconds, in UTC. UTC::to_iso8601 produces that form, as Create and Format Times shows. Any other card goes in through keyword or keywords.

write_to picks FITS or XISF from the extension. With .xisf, the keywords go into the XISF file as FITS keywords, and the WCS is also written as XISF astrometric solution properties. XISF Files covers that mapping.

Which sample types each method takes

AstroImage writes the buffer in its own type. Each format has its own list of types it can store, so the method you call limits the element type of your Vec:

MethodElement types
write_fitsu8, i8, i16, u16, i32, u32, i64, u64, f32, f64
write_xisfu8, u16, u32, u64, f32, f64
write_tou8, u16, u32, u64, f32, f64

write_to takes only the types both formats store, because it decides the format at run time. FITS stores i8, u16, u32 and u64 as the integer type of the same width with the other signedness, plus a BZERO offset, so write_fits shifts each sample and writes BZERO for you. A Vec<u16> from a camera driver comes back from Image::open as U16. Since write_fits sets BZERO itself, a BZERO or BSCALE keyword you pass with one of these types is an error. u64 samples can’t be tile-compressed.

A multi-channel buffer must be planar: every red sample, then every green, then every blue, with dimensions of [width, height, 3]. That’s the order both formats store. An Image holds RGB interleaved instead, so pick the type that matches the order your buffer already has.

Write a camera frame with Image

Image takes any PixelData variant, including U16, and has the same metadata setters as AstroImage:

use celestial_images::formats::image::Image;
use celestial_images::formats::pixel_data::PixelData;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // One frame from the camera driver: 16-bit samples, row by row
    let raw: Vec<u16> = vec![1000; 3008 * 3008];

    let mut frame = Image::new(PixelData::U16(raw), [3008, 3008]);
    frame
        .object("NGC 7000")
        .filter("Ha")
        .exposure(300.0)
        .temperature(-10.0)
        .gain(100.0)
        .binning(1, 1)
        .date_obs("2026-08-14T03:21:07.250");
    frame.save("light_0001.fits")?;

    let back = Image::open("light_0001.fits")?;
    println!("first sample: {:?}", back.pixels.as_u16().map(|p| p[0]));
    for name in ["CCD-TEMP", "GAIN", "XBINNING"] {
        println!("{name:<8} = {:?}", back.get(name).value());
    }
    Ok(())
}
first sample: Some(1000)
CCD-TEMP = Some(Real(-10.0))
GAIN     = Some(Real(100.0))
XBINNING = Some(Integer(1))

Image::save writes DATASUM and CHECKSUM cards, as write_fits does. A file saved again gets fresh cards in place of the old ones.

To write a WCS into an Image, add the cards from wcs.to_keywords() with set_keyword. Each WcsKeyword converts into a Keyword with From.

Compress the output

Both writers can tile-compress a FITS file. On AstroImage, call .compressed(CompressionAlgorithm::Rice) before write_fits or write_to, and optionally .tile_size(width, height). On Image, call save_fits_compressed(path, algorithm, tile_size) instead of save. For XISF, XisfWriter compresses data blocks. Tile Compression and XISF Files cover both.

Where next