App or game developer always need a tool / script that convert your static or dynamic html to image . As in case if you are php developer and want to know how to convert html to jpeg image in simple way then this article is for you.
In this post you will learn how to convert html to image. I have to discover this trick when I was making a facebook game and script need to post dynamic game score on user’s wall. My client provided me the html of result webpage but all we need is just to convert this dynamic result html to jpeg.
This is the simple way and you have to compromise with its image quality.This html to image php script does not require any external api or GD Library, Most of the server does not have GD library extension.
As i told if we have some html and it is changeable html or php page and we want to capture it as snapshot.
Facebook application development
For Tutorial website
For development purposes
What we don’t need to convert html to image with php
We will create html to snapshot without using any php gd library or any third party API. Now we will convert html to pdf with php
Without using third party API.
Without using php GD Library.
Without any shell script or window command.
What we need to convert html to image
How it Works
The idea behind conversion is simple. We will first convert html of any webpage to pdf using HTML2PDF utility and then we will convert pdf doc to an image.
convert html to image
Load html from file or url
This is example how to convert webpage into image with php script
For more details on how this works, see Creating an image.
Example API response:
Authentication with PHP
Your username is your User ID and your password is your API Key. Both of these are available from the dashboard. The PHP code sample demonstrates how to authenticate your request.
You can signup for a free API key to get started.
PHP example code
This PHP code example sends an HTTP POST to the https://hcti.io/v1/image API. Converting your HTML/CSS to an image with PHP.
Welcome to a tutorial on how to convert HTML to an image in PHP. So you have a PHP project that needs to convert HTML into an image? Bad news, there are no free “HTML to image” libraries at the time of writing.
Use the browser headless mode to open a URL and capture a screenshot.
Open the HTML in a browser, capture a screenshot, then send it to PHP for processing.
Use an online conversion service.
Convert HTML to PDF first, then save the PDF as an image.
It’s kind of roundabout, but possible – Read on for the examples!
TABLE OF CONTENTS
DOWNLOAD & NOTES
Here is the download link to the example code, so you don’t have to copy-paste everything.
EXAMPLE CODE DOWNLOAD
Just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
SUPPORT
600+ free tutorials & projects on Code Boxx and still growing. I insist on not turning Code Boxx into a «paid scripts and courses» business, so every little bit of support helps.
PHP HTML TO IMAGE
All right, let us now get into the possible ways of converting HTML into an image in PHP.
This snippet simply runs chrome --headless --screenshot="demoA.png" --window-size=1080,1920 "https://code-boxx.com" in the command line.
“Headless mode” will open the browser but does not show it on the screen.
That is, silently open https://code-boxx.com and take a screenshot.
For those who are lost – Create your own HTML file, for example, http://localhost/foo.html . Use headless mode to access that HTML file and take a screenshot, that’s your “HTML to image” conversion.
P.S. Both Opera and Edge are also Chromium-based, capable of running in headless mode. Firefox can also run in headless mode. Not too sure about the half-eaten apple.
2) BROWSER SCREENSHOT
2A) HTML & JAVASCRIPT
TEST PAGE
Hello world!
(B1) We are using HTML2Canvas to capture a screenshot
(B2) Upload the screenshot to the server.
P.S. You can create a bat (Windows) or sh (Linux/Mac) to open a web browser. For example, chrome.exe --app=http://localhost/2a-page.php . Then, set it to run on schedule, or use PHP exec() to call it on demand.
2B) PHP
In this example, we simply save the uploaded screenshot to a PNG file. In your project, you can pretty much do whatever you want – Save into a database, save into a cloud drive, send via email, etc…
(B) Send the HTML/CSS to HCTI, create a PNG image.
(C) Fetch the generated image, do whatever is required – We simply save it in this example.
P.S. Remember to sign up for a free account and change the user/password to your own in (B1).
4) HTML TO PDF, PDF TO IMAGE
// (A) HTML CONTENT $html = TEST PAGE
Hello world!
HTML; // (B) HTML TO PDF require "vendor/autoload.php"; $mpdf = new \Mpdf\Mpdf(); $mpdf->WriteHTML($html); $mpdf->Output("demoD.pdf"); // (C) PDF TO IMAGE $image = new Imagick("demoD.pdf"); $image->setImageFormat("jpg"); $image->writeImage("demoD.jpg");
MPDF – The easiest way is to use Composer composer require mpdf/mpdf .
ImageMagick – The installation is kind of confusing, and cannot be explained in a paragraph… You will need to do some research on your own.
But yep, this is pretty much “HTML to PDF”, then “PDF to image”.
EXTRAS
That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.
WHICH IS THE BEST METHOD?
Browser Screenshot (headless or not) – I am personally leaning towards this method, simply because it’s the most accurate and free.
Online Service – Works if you are running a command line PHP, but probably need to pay if you need to process many of such images.
HTML to PDF to image – Works as well, but inefficient.
LINKS & REFERENCES
THE END
Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!
Leave a Comment Cancel Reply
Search
Breakthrough Javascript
Take pictures with the webcam, voice commands, video calls, GPS, NFC. Yes, all possible with Javascript - Check out Breakthrough Javascript!
Socials
About Me
W.S. Toh is a senior web developer and SEO practitioner with over 20 years of experience. Graduated from the University of London. When not secretly being an evil tech ninja, he enjoys photography and working on DIY projects.
Code Boxx participates in the eBay Partner Network, an affiliate program designed for sites to earn commission fees by linking to ebay.com. We also participate in affiliate programs with Bluehost, ShareASale, Clickbank, and other sites. We are compensated for referring traffic.
Всем привет,необходимо сохранить html страницу в картинку средствами php,вопрос может кто знает подобные библиотеки,сторонние сервисы не очень хотелось бы использовать.
Я использую PHP PhantomJs. Он не идеален, но для моих потребностей подходит. Ну и конечно сервер на котором это будет работать должен уметь запускать бинарные PHP скрипты.
Но если вам необходимо собрать DOM более качественно, придерживаясь самых современных стандартов, то изучайте Selenium. Например на Питоне он очень прост в использовании: