code: def save(img: FileBasedImage, filename: FileSpec, **kwargs) -> None:
      r"""Save an image to file adapting format to `filename`
  
      Parameters
      ----------
      img : ``SpatialImage``
         image to save
      filename : str or os.PathLike
         filename (often implying filenames) to which to save `img`.
      \*\*kwargs : keyword arguments
          Keyword arguments to format-specific save
  
      Returns
      -------
      None
      """
      filename = _stringify_path(filename)
  
      # Save the type as expected
      try:
          img.to_filename(filename, **kwargs)
      except ImageFileError:
          pass
      else:
          return
  
      # Be nice to users by making common implicit conversions
      froot, ext, trailing = splitext_addext(
          filename, _compressed_suffixes
      )
      lext = ext.lower()
  
      # Special-case Nifti singles and Pairs
      # Inline imports, as this module really shouldn't reference any image type
      from .nifti1 import Nifti1Image, Nifti1Pair
      from .nifti2 import Nifti2Image, Nifti2Pair
  
      converted: FileBasedImage
      if type(img) == Nifti1Image and lext in (".img", ".hdr"):
          converted = Nifti1Pair.from_image(img)
      elif type(img) == Nifti2Image and lext in (".img", ".hdr"):
          converted = Nifti2Pair.from_image(img)
      elif type(img) == Nifti1Pair and lext == ".nii":
          converted = Nifti1Image.from_image(img)
      elif type(img) == Nifti2Pair and lext == ".nii":
          converted = Nifti2Image.from_image(img)
      else:  # arbitrary conversion
          valid_klasses = [
              klass
              for klass in all_image_classes
              if lext in klass.valid_exts
          ]
          if not valid_klasses:  # if list is empty
              raise ImageFileError(
                  f'Cannot work out file type of "{filename}"'
              )
  
          # Got a list of valid extensions, but that's no guarantee
          #   the file conversion will work. So, try each image
          #   in order...
          for klass in valid_klasses:
              try:
                  converted = klass.from_image(img)
                  break
              except Exception as e:
                  err = e
          else:
              raise err
  
      converted.to_filename(filename, **kwargs)
  
file_path: nibabel/nibabel/loadsave.py
imports: from __future__ import annotations
  import os
  import typing
  import numpy
  from .arrayproxy import is_proxy
  from .deprecated import deprecate_with_version
  from .filebasedimages import ImageFileError
  from .filename_parser import _stringify_path, splitext_addext
  from .imageclasses import all_image_classes
  from .openers import ImageOpener
label_desc: Use image node_id 4 for calling a global function with example usage: save(img, filename) without return types