Skip to content

Fix GH-23459: Improve imagegrabscreen() and imagegrabwindow() performance on Windows - #23485

Open
LamentXU123 wants to merge 1 commit into
php:masterfrom
LamentXU123:opt-2
Open

Fix GH-23459: Improve imagegrabscreen() and imagegrabwindow() performance on Windows#23485
LamentXU123 wants to merge 1 commit into
php:masterfrom
LamentXU123:opt-2

Conversation

@LamentXU123

@LamentXU123 LamentXU123 commented Aug 28, 2026

Copy link
Copy Markdown
Member

The original implementation of imagegrabscreen is super weird. It currently calls GetPixel() once for every pixel after capturing the desktop (???). On a 1560x1040 display, this results in more than 1.6 million GDI calls and takes around 2.8 seconds locally. (?????) Besides, I find a out-of-bound off-by-one read in the original implementation. This is also true for imagegrabwindow. They share the same exact logic and don't even make this out as a shared helper...

This is a easy fix. Anyways, now we retrieve the bitmap in a single GetDIBits() call as a top-down 32-bit DIB, then convert the returned RGBQUAD buffer directly into the GD true-color image.

I run the benchmark locally with a 1560×1040 pic.

Before: 2.997434s
After: 0.003682s

A 814x optimization in total. Fixes #23459

@LamentXU123
LamentXU123 requested a review from devnexen as a code owner August 28, 2026 07:55
@LamentXU123 LamentXU123 changed the title Fix GH-23459: Improve imagegrabscreen() performance on Windows Fix GH-23459: Improve imagegrabscreen() and imagegrabwindow() performance on Windows Aug 28, 2026
@devnexen

Copy link
Copy Markdown
Member

Not out of bounds from what I see ... The y <= Height / x <= Width bound is a genuine off-by-one and should have been <, but neither side of the loop body touches memory out of bounds: if you think I m wrong please add a test.

@LamentXU123

Copy link
Copy Markdown
Member Author

Blerg I made a typo here. Yeah what I meant is off-by-one :)

Comment thread UPGRADING
. Made splitText() faster and consume less memory.

- GD:
. Improved performance of imagegrabscreen() and imagegrabwindow() on

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.

should this also mention imagbmp from #23457 ?

@devnexen

devnexen commented Aug 28, 2026

Copy link
Copy Markdown
Member

nope. already fixed and different issue anyway (as in its fix can t apply here).

@LamentXU123

Copy link
Copy Markdown
Member Author

I think it is reasonable to document the optimization in #23457 in the UPGRADING file. But that's a different story. I will take care of this in a different commit.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

imagegrabscreen() is extremely slow

3 participants