Social Media Image Kit

Social Media Image Kit

Custom Renderers

Custom renderers allow you change how social media images are generated from HTML. Social Media Image Kit ships with a Browsershot renderer out of the box, if you landed on this page looking to change it's configuration you might consider the Configuring Browershot article before looking at a custom renderer.

#Creating Custom Renderers

All custom renderers must implement the Stillat\SocialMediaImageKit\Contracts\HtmlRenderer contract. Custom renderers must define a fromHtml method that accepts the following information:

  • $path: A path where the generated image should be saved on the local file system. The default image generator must be able to access both the generated image, as well as a functional Statamic instance.

  • $html: The HTML to be converted into an image.

  • $details: Additional information about the image to be generated, such as the width and height.

Below is a simplified versions of the provided Browsershot render for reference:

3namespace Stillat\SocialMediaImageKit\Rendering;
5use Spatie\Browsershot\Browsershot;
6use Stillat\SocialMediaImageKit\Contracts\HtmlRenderer;
7use Stillat\SocialMediaImageKit\ImageDetails;
9class BrowsershotRenderer implements HtmlRenderer
11 public function fromHtml(string $path, string $html, ImageDetails $details): bool
12 {
13 $browserhotInstance = Browsershot::html($html)
14 ->windowSize($details->width, $details->height)
15 ->waitUntilNetworkIdle();
17 $browserhotInstance->save($path);
19 return file_exists($path);
20 }

Each renderer implementation must return a true/false value indicating if the file generation process was a success. The simplest way to implement this behavior is to check if the generated file exists, but other custom logic may also be implemented, depending on the renderer's implementation.

#Configuring Custom Renderers

Social Media Image Kit must be configured to use custom renderers. This can be done within the generation.php configuration file:

3return [
5 // ...
8 /*
9 |--------------------------------------------------------------------------
10 | HTML Renderer Configuration
11 |--------------------------------------------------------------------------
12 |
13 | Which HTML rendering engine should be used to generate the social media
14 | images. By default, the Social Media Image Kit does not ship with a
15 | renderer. You must install or create your own renderer. For more
16 | information, please see the following documentation page:
17 |
18 */
20 'html_renderer' => \Stillat\SocialMediaImageKit\Rendering\BrowsershotRenderer::class,
22 // ...

Some absolutely amazing

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.