How do you create an image of a web page in PHP?

2019-06-21 11:53发布

问题:

How can you render and save a web page as an image in PHP, probably with a width of 600px. How can I render a page in PHP without using a browser? How can I save it with a given resolution and image format (jpeg)? The functionality is similar to Google Preview, except it will not be displayed in a rollover.

Similar to this question, which is answered in C#. How to save a web page as image

Thanks!

回答1:

You should get wkhtmltoimage, which is very easy to utilize from within PHP:

exec("../wkhtmltoimage --crop-w 600 http://example.com/ output.png");

There are other options, and instead of --crop-w or --width 600 it might be better to downscale it using GD or imagemagick afterwards.



回答2:

You can't do this in pure PHP, you'll always need an external renderer to get a good result.

Your best bet would be to use an external service such as the browsershots.org API, this way you won't produce extra load on your server.

If you have resources to burn, you could use another method (still running on your server, just not PHP) called wkhtmltoimage as in mario's answer. Just remember that this wouldn't be recommended (infact, probably not even possible) on shared hosting.