How We Use PHP to Generate Instagram Images
In this brief tutorial, we learn how one company uses PHP to create automated Instagram posts with quotes and avatars.
Join the DZone community and get the full member experience.Join For Free
Unlike most people's Instagram, our Instagram is almost 100% automatic. For example, we use code to generate our images.
Why Automatic Images
On our website, we interview people who do great in fitness. Most of the interviews have great, motivating quotes that people in fitness love, so, inspired by Foundr's Instagram, it was kind of obvious that our Instagram images should also be quotes.
All our interviews have a personalized avatar attached to them, so we decided to also add the avatar and the name of the person behind the quote to each image.
Getting the Quotes
In our interviews, the quotes are shown using a Wordpress shortcode (since our site runs on WP). Like this:
[quote]I once did 5,500 burpees in 24 hours.[/quote]
The shortcode above leads to this being generated on the page (live here):
When the shortcode is run, the quote is saved to a custom table in the database (wp_[prefix]_quotes). Once a week, an editor take a look at any new quotes and mark the ones that might do well on Instagram.
Putting the Images Together
First, we create a base image, which is just a white image with the right dimensions. In our case, that's 600 x 600 since that resolution is good enough for Instagram and square-like Instagram likes.
We then set up the colors for the texts:
Adding the text to the images is done using
imagettftext(). That function takes a lot of parameters and it's no secret that we tried many different positions and font sizes before the text ended up looking perfect on the images (especially because the names and quotes all have different lengths).
We add one line at a time to the image using
imagettftext(). Like this:
The avatar image we add using
imagecopyresampled(). Like this:
$avatar_size is the size of the avatar image — and since our avatar images are square, we can use the same parameter twice.
Finally, we add our logo. Smart readers might have spotted the two orange "//" in our logo could be text — and yes, that's what it is. 2 x 3 "/" characters placed very close to each other with
After the logo has been added, we just need to save the image and drop the temporary image we have been working on:
Other temporary images must also be destroyed, like
Opinions expressed by DZone contributors are their own.