Using Browsershot to create Open Graph images

Wednesday Nov 30th 2022
3 min read

I rarely use photos on this site and I knew this from the start. I decided to generate Open Graph images myself and it had to be automatic process. So of course Spatie had a package for that called Browsershot.

I have actually done this on my finnish travel blog before but now I decided to do without background images.

Using Laravel and Spaties Browsershot package it is quite easy to create an image. It needs only a Puppeteer and then it works like magic.

I have article-og view that I give $article parameter. Then it has everything it needs to generate nice looking Open Graph image.

First I make base64 image of the view.

1$base64Image = Browsershot::html(
2 view('article-og', compact('article'))->render()
4 ->showBackground()
5 ->windowSize(1200, 630)
6 ->base64Screenshot();

Then I just save it to my articles media collection (using another Spatie package, Medialibrary)

2 ->usingFileName("{$article->slug}-og.png")
3 ->toMediaCollection('og');

And then it is easy to get that image on the article page and place it on the right place. End result is similar to this image:

Example of og image

As you can see the image has it all that I want. It is super easy to modify since it uses Tailwind CSS and simple html.

On the travel blog I mentioned I use background image and again Tailwind and html to style it. End result is like this.

Travel blog og image example

I like to make Open Graph images like this since it gives a bit of a special touch to the site when it is shared on the social media. I also suggest to make the images in a Laravel Job so it is a bit smarter way to do it.

For example I have a scheduled command that checks if article needs to be published. When it is then a job will run that makes my Open Graph image. I only need to set the time when I want the article be published at and the app does the rest. How great is that!

How do you generate Open Graph images?


No comments yet…

Log in to make a comment...