code: def _encode_image(image, image_format=None, fobj=None):
      """Encodes and writes an image in a Numpy array to a file object.
  
      Args:
        image: A numpy array with shape (height, width, channels).
        image_format: Encode and write the image in this format. If None, JPEG is
          used.
        fobj: File object to write the encoded image. Random access (seek) is
          required. If None, it creates a BytesIO file.
  
      Returns:
        Resulting file object. If fobj was given, the functions returns it.
      """
      if len(image.shape) != 3:
          raise ValueError(
              "The image should have shape (height, width, channels)"
          )
  
      # By default, for images with alpha channel use PNG, otherwise use JPEG.
      if image_format is None:
          image_format = "JPEG"
  
      # Remove extra channel for grayscale images, or PIL complains.
      if image.shape[-1] == 1:
          image = image.reshape(image.shape[:-1])
  
      fobj = fobj or io.BytesIO()
      image = tfds.core.lazy_imports.PIL_Image.fromarray(image)
      image.save(fobj, format=image_format)
      fobj.seek(0)
      return fobj
  
file_path: datasets/tensorflow_datasets/testing/fake_data_generation/sun397.py
imports: import io
  import os
  import random
  import tarfile
  import tempfile
  from absl import app
  from absl import flags
  import md5
  import numpy
  from tensorflow_datasets.core import utils
  import tensorflow_datasets.public_api
label_desc: Use image node_id 3 for calling a global function with example usage: _encode_image(image, image_format, fobj) and returns: fobj