code: def _ensure_image_size_and_format(
      image_data: bytes, width: int, image_format: ImageFormat
  ) -> bytes:
      """Resize an image if it exceeds the given width, or if exceeds
      MAXIMUM_CONTENT_WIDTH. Ensure the image's format corresponds to the given
      ImageFormat. Return the (possibly resized and reformatted) image bytes.
      """
      pil_image = Image.open(io.BytesIO(image_data))
      actual_width, actual_height = pil_image.size
  
      if width < 0 and actual_width > MAXIMUM_CONTENT_WIDTH:
          width = MAXIMUM_CONTENT_WIDTH
  
      if width > 0 and actual_width > width:
          # We need to resize the image.
          new_height = int(1.0 * actual_height * width / actual_width)
          pil_image = pil_image.resize(
              (width, new_height), resample=Image.BILINEAR
          )
          return _PIL_to_bytes(
              pil_image, format=image_format, quality=90
          )
  
      if pil_image.format != image_format:
          # We need to reformat the image.
          return _PIL_to_bytes(
              pil_image, format=image_format, quality=90
          )
  
      # No resizing or reformatting necessary - return the original bytes.
      return image_data
  
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 10 for calling a global function with example usage: _ensure_image_size_and_format(image_data, width, image_format) and returns: image_data, _PIL_to_bytes, _PIL_to_bytes