Repository: AUTOMATIC1111/stable-diffusion-webui

Issue:
[Bug]: Call ControlNet API failed
### Is there an existing issue for this?

- [X] I have searched the existing issues and checked the recent builds/commits

### What happened?

Call ControlNet through the API. It raise an error `cannot write mode RGBA as JPEG`.
ControlNet:
- Preprocessor: inpaint_only+lama
- Model: control_v11p_sd15_inpaint [ebff9138]
- ControlNet Version: v1.1.231


### Steps to reproduce the problem

1. Call ControlNet through the API "/sdapi/v1/txt2img"
2. ControlNet payload like this:
```json
{
    "prompt": "a handsome man",
    "negative_prompt": "",
    "batch_size": 1,
    "steps": 30,
    "width": 1536,
    "height": 768,
    "cfg_scale": 7,
    "alwayson_scripts": {
        "controlnet": {
            "args": [
                {
                    "input_image": "encoded_image",
                    "module": "inpaint_only+lama",
                    "model": "control_v11p_sd15_inpaint [ebff9138]",
                    "control_mode": 2,
                    "resize_mode": "Resize and Fill"
                }
            ]
        }
    }
}
```


### What should have happened?

ControlNet should be called correctly, and the picture generated.

### Version or Commit where the problem happens

v1.3.2

### What Python version are you running on ?

Python 3.10.x

### What platforms do you use to access the UI ?

Linux

### What device are you running WebUI on?

Nvidia GPUs (RTX 20 above)

### Cross attention optimization

xformers

### What browsers do you use to access the UI ?

Google Chrome

### Command Line Arguments

```Shell
--api --xformers --server-name=0.0.0.0 --enable-insecure-extension-access --device-id=0
```


### List of extensions

sd-webui-controlnet

### Console logs

```Shell
╭───────────────────── Traceback (most recent call last) ──────────────────────╮
│ /home/jovijovi/anaconda3/envs/automatic/lib/python3.10/site-packages/PIL/Jp  │
│ egImagePlugin.py:640 in _save                                                │
│                                                                              │
│   639 │   try:                                                               │
│ ❱ 640 │   │   rawmode = RAWMODE[im.mode]                                     │
│   641 │   except KeyError as e:                                              │
│                                                                              │
│ ╭───────────────────────────────── locals ─────────────────────────────────╮ │
│ │ filename = ''                                                            │ │
│ │       fp = <_io.BytesIO object at 0x7f6f3474f9c0>                        │ │
│ │       im = <PIL.Image.Image image mode=RGBA size=1536x768 at             │ │
│ │            0x7F6DB7636470>                                               │ │
│ │      msg = 'cannot write mode RGBA as JPEG'                              │ │
│ ╰──────────────────────────────────────────────────────────────────────────╯ │
╰──────────────────────────────────────────────────────────────────────────────╯
KeyError: 'RGBA'

The above exception was the direct cause of the following exception:

╭───────────────────── Traceback (most recent call last) ──────────────────────╮
│ /mnt/local/dev/generator-auto1111/modules/api/api.py:154 in                  │
│ exception_handling                                                           │
│                                                                              │
│   153 │   │   try:                                                           │
│ ❱ 154 │   │   │   return await call_next(request)                            │
│   155 │   │   except Exception as e:                                         │
│                                                                              │
│ ╭───────────────────────────────── locals ─────────────────────────────────╮ │
│ │        call_next = <function                                             │ │
│ │                    BaseHTTPMiddleware.__call__.<locals>.call_next at     │ │
│ │                    0x7f6d8c1004c0>                                       │ │
│ │                e = OSError('cannot write mode RGBA as JPEG')             │ │
│ │ handle_exception = <function api_middleware.<locals>.handle_exception at │ │
│ │                    0x7f6db4321a20>                                       │ │
│ │          request = <starlette.requests.Request object at 0x7f6d8c55d900> │ │
│ ╰──────────────────────────────────────────────────────────────────────────╯ │
│                                                                              │
│ /home/jovijovi/anaconda3/envs/automatic/lib/python3.10/site-packages/starle  │
│ tte/middleware/base.py:84 in call_next                                       │
│                                                                              │
│                           ... 23 frames hidden ...                           │
│                                                                              │
│ /home/jovijovi/anaconda3/envs/automatic/lib/python3.10/site-packages/PIL/Im  │
│ age.py:2432 in save                                                          │
│                                                                              │
│   2431 │   │   try:                                                          │
│ ❱ 2432 │   │   │   save_handler(self, fp, filename)                          │
│   2433 │   │   except Exception:                                             │
│                                                                              │
│ ╭───────────────────────────────── locals ─────────────────────────────────╮ │
│ │      created = False                                                     │ │
│ │          ext = ''                                                        │ │
│ │     filename = ''                                                        │ │
│ │       format = 'JPEG'                                                    │ │
│ │           fp = <_io.BytesIO object at 0x7f6f3474f9c0>                    │ │
│ │      open_fp = False                                                     │ │
│ │       params = {                                                         │ │
│ │                │   'exif':                                               │ │
│ │                b'Exif\x00\x00MM\x00*\x00\x00\x00\x08\x00\x01\x87i\x00\x… │ │
│ │                │   'quality': 80                                         │ │
│ │                }                                                         │ │
│ │     save_all = False                                                     │ │
│ │ save_handler = <function _save at 0x7f6eae53c430>                        │ │
│ │         self = <PIL.Image.Image image mode=RGBA size=1536x768 at         │ │
│ │                0x7F6DB7636470>                                           │ │
│ ╰──────────────────────────────────────────────────────────────────────────╯ │
│                                                                              │
│ /home/jovijovi/anaconda3/envs/automatic/lib/python3.10/site-packages/PIL/Jp  │
│ egImagePlugin.py:643 in _save                                                │
│                                                                              │
│   642 │   │   msg = f"cannot write mode {im.mode} as JPEG"                   │
│ ❱ 643 │   │   raise OSError(msg) from e                                      │
│   644                                                                        │
│                                                                              │
│ ╭───────────────────────────────── locals ─────────────────────────────────╮ │
│ │ filename = ''                                                            │ │
│ │       fp = <_io.BytesIO object at 0x7f6f3474f9c0>                        │ │
│ │       im = <PIL.Image.Image image mode=RGBA size=1536x768 at             │ │
│ │            0x7F6DB7636470>                                               │ │
│ │      msg = 'cannot write mode RGBA as JPEG'                              │ │
│ ╰──────────────────────────────────────────────────────────────────────────╯ │
╰──────────────────────────────────────────────────────────────────────────────╯
OSError: cannot write mode RGBA as JPEG
```


### Additional information

_No response_


Discussion:

Resolving patch:
diff --git a/modules/api/api.py b/modules/api/api.py
--- a/modules/api/api.py
+++ b/modules/api/api.py
@@ -84,6 +84,8 @@ def encode_pil_to_base64(image):
             image.save(output_bytes, format="PNG", pnginfo=(metadata if use_metadata else None), quality=opts.jpeg_quality)
 
         elif opts.samples_format.lower() in ("jpg", "jpeg", "webp"):
+            if image.mode == "RGBA":
+                image = image.convert("RGB")
             parameters = image.info.get('parameters', None)
             exif_bytes = piexif.dump({
                 "Exif": { piexif.ExifIFD.UserComment: piexif.helper.UserComment.dump(parameters or "", encoding="unicode") }


Test patch: