Only close file handle in ImagePalette.save() if it was opened internally by bysiber · Pull Request #9444 · python-pillow/Pillow
ImagePalette.save() unconditionally calls fp.close() at the end, even when the file handle was passed in by the caller. This closes the caller's file object, causing any subsequent operations on it to fail with ValueError: I/O operation on closed file.
When fp is a string (filename), save() correctly opens the file internally — but only that internally-opened handle should be closed. The fix tracks whether we opened the file and only closes it in that case, wrapped in try/finally to avoid leaking the handle if a write fails.