Skip to content

Correct writing buffer to file in PyEncoder encode_to_file() - #10098

Open
radarhere wants to merge 2 commits into
python-pillow:mainfrom
radarhere:encode_to_file
Open

radarhere wants to merge 2 commits into
python-pillow:mainfrom
radarhere:encode_to_file

Conversation

@radarhere

@radarhere radarhere commented Oct 2, 2026 •

Copy link
Copy Markdown
Member

Resolves #10096

PyEncoder.encode_to_file() is meant to mirror the behaviour of our C encoders.

In C's _encode_to_file(), we have

Pillow/src/encode.c

Lines 201 to 204 in 9712fff

status = encoder->encode(encoder->im, &encoder->state, buf, bufsize);
if (status > 0) {
if (write(fh, buf, status) < 0) {

In Python, we have

Pillow/src/PIL/ImageFile.py

Lines 933 to 935 in 9712fff

status, errcode, buf = self.encode(bufsize)
if status > 0:
os.write(fh, buf[status:])

There seems to have been a fairly basic mistake here in Python - we should be writing status number of bytes, not removing status number of bytes before writing. buf[:status], not buf[status:].

Comment thread src/PIL/ImageFile.py Outdated
Comment on lines +933 to +935
status, errcode, buf = self.encode(bufsize)
if status > 0:
os.write(fh, buf[status:])
os.write(fh, buf[:status])

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

status seems a misnomer?

Suggested change
status, errcode, buf = self.encode(bufsize)
if status > 0:
os.write(fh, buf[status:])
os.write(fh, buf[:status])
n_bytes, errcode, buf = self.encode(bufsize)
if n_bytes > 0:
os.write(fh, buf[:n_bytes])

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've pushed bytes_consumed after https://pillow.readthedocs.io/en/stable/handbook/writing-your-own-image-plugin.html#transforming

It is the codec’s responsibility to pull as much data as possible out of the buffer and return the number of bytes consumed.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants