code: def image_to_url(
      image: AtomicImage,
      width: int,
      clamp: bool,
      channels: Channels,
      output_format: ImageFormatOrAuto,
      image_id: str,
  ) -> str:
      """Return a URL that an image can be served from.
      If `image` is already a URL, return it unmodified.
      Otherwise, add the image to the MediaFileManager and return the URL.
  
      (When running in "raw" mode, we won't actually load data into the
      MediaFileManager, and we'll return an empty URL.)
      """
  
      image_data: bytes
  
      # Strings
      if isinstance(image, str):
          # Unpack local SVG image file to an SVG string
          if image.endswith(".svg") and not image.startswith(
              ("http://", "https://")
          ):
              with open(image) as textfile:
                  image = textfile.read()
  
          # Following regex allows svg image files to start either via a "<?xml...>" tag
          # eventually followed by a "<svg...>" tag or directly starting with a "<svg>" tag
          if re.search(
              r"(^\s?(<\?xml[\s\S]*<svg\s)|^\s?<svg\s|^\s?<svg>\s)",
              image,
          ):
              if "xmlns" not in image:
                  # The xmlns attribute is required for SVGs to render in an img tag.
                  # If it's not present, we add to the first SVG tag:
                  image = image.replace(
                      "<svg",
                      '<svg xmlns="http://www.w3.org/2000/svg" ',
                      1,
                  )
              # Convert to base64 to prevent issues with encoding:
              image_b64_encoded = base64.b64encode(
                  image.encode("utf-8")
              ).decode("utf-8")
              # Return SVG as data URI:
              return f"data:image/svg+xml;base64,{image_b64_encoded}"
  
          # If it's a url, return it directly.
          try:
              p = urlparse(image)
              if p.scheme:
                  return image
          except UnicodeDecodeError:
              # If the string runs into a UnicodeDecodeError, we assume it is not a valid URL.
              pass
  
          # Otherwise, try to open it as a file.
          try:
              with open(image, "rb") as f:
                  image_data = f.read()
          except Exception:
              # When we aren't able to open the image file, we still pass the path to
              # the MediaFileManager - its storage backend may have access to files
              # that Streamlit does not.
              mimetype, _ = mimetypes.guess_type(image)
              if mimetype is None:
                  mimetype = "application/octet-stream"
  
              url = runtime.get_instance().media_file_mgr.add(
                  image, mimetype, image_id
              )
              caching.save_media_data(image, mimetype, image_id)
              return url
  
      # PIL Images
      elif isinstance(image, (ImageFile.ImageFile, Image.Image)):
          format = _validate_image_format_string(image, output_format)
          image_data = _PIL_to_bytes(image, format)
  
      # BytesIO
      # Note: This doesn't support SVG. We could convert to png (cairosvg.svg2png)
      # or just decode BytesIO to string and handle that way.
      elif isinstance(image, io.BytesIO):
          image_data = _BytesIO_to_bytes(image)
  
      # Numpy Arrays (ie opencv)
      elif isinstance(image, np.ndarray):
          image = _clip_image(
              _verify_np_shape(image),
              clamp,
          )
  
          if channels == "BGR":
              if len(image.shape) == 3:
                  image = image[:, :, [2, 1, 0]]
              else:
                  raise StreamlitAPIException(
                      'When using `channels="BGR"`, the input image should '
                      "have exactly 3 color channels"
                  )
  
          # Depending on the version of numpy that the user has installed, the
          # typechecker may not be able to deduce that indexing into a
          # `npt.NDArray[Any]` returns a `npt.NDArray[Any]`, so we need to
          # ignore redundant casts below.
          image_data = _np_array_to_bytes(
              array=cast("npt.NDArray[Any]", image),  # type: ignore[redundant-cast]
              output_format=output_format,
          )
  
      # Raw bytes
      else:
          image_data = image
  
      # Determine the image's format, resize it, and get its mimetype
      image_format = _validate_image_format_string(
          image_data, output_format
      )
      image_data = _ensure_image_size_and_format(
          image_data, width, image_format
      )
      mimetype = _get_image_format_mimetype(image_format)
  
      if runtime.exists():
          url = runtime.get_instance().media_file_mgr.add(
              image_data, mimetype, image_id
          )
          caching.save_media_data(image_data, mimetype, image_id)
          return url
      else:
          # When running in "raw mode", we can't access the MediaFileManager.
          return ""
  
imports: import base64
  import io
  import mimetypes
  import re
  from enum import IntEnum
  from typing import TYPE_CHECKING, List, Optional, Sequence, Union, cast
  from urllib.parse import urlparse
  import numpy
  from PIL import GifImagePlugin, Image, ImageFile
  from typing_extensions import Final, Literal, TypeAlias
  from streamlit import runtime
  from streamlit.errors import StreamlitAPIException
  from streamlit.logger import get_logger
  from streamlit.proto.Image_pb2 import ImageList
  from streamlit.runtime import caching
  from streamlit.runtime.metrics_util import gather_metrics
label_desc: Use image node_id 12 for calling a global function with example usage: image_to_url(image, width, clamp, channels, output_format, image_id) and returns: url, str, str, image_b64_encoded, image, url