Comfy-Org / Comfy-Org/ComfyUI

Image from `/view` endpoint has wrong orientation

Open
#1,621 1 comment 0 reactions 0 assignees View on GitHub
Dominant language
Python
Stars
133k
Forks
15.7k
Avg merge
1d 7h
Merged PRs (30d)
158

Description

## What's the problem?

`/view` endpoint returns image with wrong orientation when:
1. The image has `EXIF orientation` **AND**
2. `preview` parameter is passed **OR** `channel` parameter is not "rgba"

![Untitled-2](https://github.com/comfyanonymous/ComfyUI/assets/9688367/729ee04b-046f-4607-9dc9-62dcd29c5f34)

## Why does it happen?

```python
# server.py / view_image()
# modified a little bit for better understanding
...
if 'preview' in request.rel_url.query:
with Image.open(file) as img:
... # do some image processing
return web.Response(body=buffer.read(), content_type='image/png',
headers={"Content-Disposition": f"filename=\"{filename}\""})

elif channel == 'rgb':
with Image.open(file) as img:
... # do some image processing
return web.Response(body=buffer.read(), content_type='image/png',
headers={"Content-Disposition": f"filename=\"{filename}\""})

elif channel == 'a':
with Image.open(file) as img:
... # same here
return web.Response(body=alpha_buffer.read(), content_type='image/png',
headers={"Content-Disposition": f"filename=\"{filename}\""})
else:
return web.FileResponse(file, headers={"Content-Disposition": f"filename=\"{filename}\""})
```

As you see, `view_image()` returns the original file with EXIF info in `else` condtion, and therefore the orientation in this case is correct.
However, in other cases, it opens the image, performs some image processing, and then returns the modified image without EXIF information. Therefore the resulting image will have wrong orientation if the image has EXIF orientation not equal to 1.
(Refer to [this](https://sirv.com/help/articles/rotate-photos-to-be-upright/#:~:text=EXIF%20orientation%20values,-The%208%20EXIF&text=%3D%200%20degrees%2C%20mirrored%3A%20image,and%20is%20on%20its%20side.) for more information about EXIF orientation)

## How can we fix it?

Adding the below one line will solve the problem:

```python
# right after opening the image
img = ImageOps.exif_transpose(img) # this corrects the image orientation according to the EXIF info
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.