code: def serialize_niimg(img, gzipped=True):
      """Serialize a Nifti1Image to nifti.
  
      Serialize to .nii.gz if gzipped, else to .nii Returns a `bytes` object.
  
      """
      with tempfile.TemporaryDirectory() as tmp_dir:
          tmp_dir = Path(tmp_dir)
          file_path = tmp_dir / f"img.nii{'.gz' if gzipped else ''}"
          img.to_filename(file_path)
          with file_path.open("rb") as f:
              return f.read()
  
file_path: nilearn/nilearn/_utils/testing.py
imports: import functools
  import gc
  import os
  import sys
  import tempfile
  import warnings
  from pathlib import Path
  import pytest
label_desc: Use image node_id 4 for calling a global function with example usage: serialize_niimg(img, gzipped) and returns: f