simonhamp / the-og

A pure PHP OpenGraph Image Generator
MIT License
226 stars 9 forks source link

Generation hangs with long titles #25

Open cwhite92 opened 5 months ago

cwhite92 commented 5 months ago

Thank you for the package! I'm using it on my Jigsaw static site to generate OG images for blog posts, and seeing an issue with certain post titles.

The following snippet hangs indefinitely on my machine and pegs a PHP process at 100% CPU usage:

return (new Image())
    ->accentColor('#cc0000')
    ->border()
    ->url($item->getUrl())
    ->title('Adding Unique Field to MySQL Table With Existing Records')
    ->description('Test description')
    ->background(Background::JustWaves, 0.2)
    ->toString();

Shortening the title to:

->title('Adding Unique Field to MySQL')

generates the image almost instantly.

Interestingly, it doesn't seem to just be an issue with title length, because this is successful:

->title('foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar')

However, removing spaces causes the hanging issue:

->title('foobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobar')

I source dived a bit and think I tracked the problem down to the while() loop in getFinalTextBox() in the TextBox class. It seems to have an issue fitting this specific text in the text box and loops indefinitely.

I'm happy to prepare a PR to fix this, but the code around here is pretty complicated. If you could point me in the right directly perhaps I can understand it better and propose the correct fix?

Thanks!

simonhamp commented 5 months ago

Thanks for sharing your code. This will be a good test case!

I'm certain it is that while loop that's to blame. It looks like you've found an edge case where the text cannot be trimmed further but still fails to fit the box.

I suspect it's to do with word length not fitting the box horizontally for the given font and font size.

The problem is that I've chosen not to split words (tho I think wordwrap can) because I believe that makes for awkward presentation, at least in an OG image context.

The solution I have in mind is to steadily make the font size smaller until the long word fits the width of the containing box.

That's probably not a perfect solution either to be honest, but should be workable in most scenarios.

RemiHin commented 1 month ago

@simonhamp any updates on this? Currently running in to the same issue