ホーム 暮らし How to dynamically generate og:image for small sites with limited server environments

How to dynamically generate og:image for small sites with limited server environments

雨宮 千夏 雨宮 千夏 • 更新: • 公開: • 読了約 26 分
目次

When building a website, one of the most troublesome things from the creator's perspective is the "og:image" that is displayed along with text when shared on social media.

It is certainly more eye-catching than just a link, and since it affects the click-through rate, it is definitely better to have one. However, it is often an image that is only specified as an image path in the page source and is not actually displayed on the page itself, so designers often forget to create it.

And so, when it comes time to share the page, it is not uncommon to find yourself saying, "Wait a minute, I didn't make an og:image..."

  • Since the appearance on social media is directly linked to the impression, it cannot be neglected.

  • 1200x630 pixels is recommended, but you don't always happen to have a nice image ready in this size.

  • Furthermore, when updating article content, you might not think to update the og:image.

So, as I said again, it is a hassle.

That is why, for our company's aguije site that we released just the other day, we decided to make the og:image dynamically generated to make things easier. This article explains how to do that.

What is dynamic generation of og:image?

na4327bc58982

Have you ever seen a link to an article page of a large-scale web service while browsing social media, accompanied by an og:image generated with a beautiful design template? It is not uncommon for large services to support this, and Qiita and Cookpad are examples of this.

For a service with a huge number of articles, it is too nonsensical to create each og:image by hand, so they are dynamically generated by a program. Cookpad's engineers have explained how they do it.

Although each company has a different approach, they generally do the following:

  • Capture a page designed for og:image as a screenshot using a headless browser (Chrome) on the server.

  • Save the image on the server as a cache and provide that image to crawlers from Facebook and Twitter.

That is what they must be doing.

Screenshot API services

As mentioned above, I have generally understood the method for dynamic generation. However, in the case of small-scale sites, the available server environment is limited, so

  • you cannot prepare the environment required by a headless browser.

  • You may not be able to install modules for image processing

and other such technical difficulties, or you may not have the budget for program development.

So, what should you do? You can use a "screenshot API service" that handles this difficult processing for you. After researching, the ones I found to be particularly good in terms of cost and reliability were Thum.io and ApiFlash.


Thum.io
  • Compared to ApiFlash mentioned later, it is limited to practical features, but they are necessary and sufficient.

  • Among the equivalent services I compared, the free usage limit of 1,000 shots/month is outstandingly high.

ApiFlash
  • It is highly functional with a wealth of configurable parameters when taking screenshots.

  • Since it can attach header information, it is possible to capture sites protected by Basic authentication.

  • The free usage limit is lower than Thum.io, but at 100 shots/month, it may still cover small sites.

Considering the flow for dynamic og:image generation

The implementation I performed on the aguije site is simple because it uses a screenshot API. When a crawler arrives, if the target og:image exists in the cache image directory, it returns it as is; if not, it runs the screenshot API to take and save the image.

Concerns

When a crawler visits and the og:image is not yet saved on the server, the procedure is to take a screenshot on the spot as described above. However, since image processing on the API side takes time, there is a possibility that the crawler might judge the image as having timed out during that interval.

However, since I have confirmed that the images are generated without any problems as a result, I expect that the crawler will re-fetch and correct it after some time. If that doesn't work, I plan to reconsider the flow.

What I prepared

Thum.io account

Thum.io can be issued immediately. If you just create an account and use the free tier, credit card registration was not required.

When you issue an account, an authentication code for API usage called a "Key" is issued, so be sure to keep it.

--

Capture Page

This is the page for the screenshot API to capture.

  • Since the aguije site uses WordPress as its CMS, I created an HTML/CSS coded page that determines the article content and post type by providing the article ID, and outputs the corresponding content.

  • I set the aspect ratio to 1200 (W) × 630 (H) so that it can be captured as an og:image.

The reason it is coded responsively is that part of the HTML and CSS is shared with the main site, but of course, there is no problem if you create it exactly at 1200×630 pixels.


Like other pages on the site, it is HTML/CSS coded, and since this page itself is dynamic, it can be managed centrally if you want to change the design.

--

Image acquisition program for crawlers (ogimage.php)
 <meta property="og:image" content="https://aguije.jp/wp/wp-content/themes/aguije/assets/php/ogimage.php?post_id=2">

This is a program installed for crawlers. Due to security concerns, I cannot post it as is, but the following is a simplified version with various parts omitted.

  • If the specified og:image already exists on the server, load it

  • If it does not exist, request a screenshot from Thum.io and save the acquired data as an image

The structure is to finally output the image.

<?php

	if (array_key_exists('post_id', $_GET) && $_GET['post_id']) 
		$post_id = intval($_GET['post_id']);
	

	$time = time();
	$ogimage_url = "http://aguije.jp/ogimage/?post_id=$post_id&time=$time";
	$ogimage_path = (画像ディレクトリまでの絶対パス) . "$post_id.png";

	//

	function get_ogimage ($_post_id = null) 
		global $ogimage_url;
		global $ogimage_path;

		if ($_post_id) 
			if (!file_exists($ogimage_path)) 

				$params = http_build_query(array(
					'url' => $ogimage_url,
				));

				$image_data = file_get_contents("https://image.thum.io/get/auth///width/1200/crop/630/png/wait/3/?$params");

				if (!empty($image_data)) 
					file_put_contents($ogimage_path, $image_data);
				

			
			else 

				$image_data = file_get_contents($ogimage_path);

			

			if ($image_data) 
				return $image_data;
			
			else 
				return false;
			
		
	

	//

	$result = get_ogimage($post_id);

	if ($result) 
		header('Content-type: image/png');
		header('Content-Length: ' . filesize($ogimage_path));
		header('Content-disposition: inline; filename="' . basename($ogimage_path) . '"');
		echo get_ogimage($post_id);
	

?>

Screenshot request to Thum.io

Simply request the URL to the API as shown below, and the screenshot image data for the specified URL will be returned.

https://image.thum.io/get/auth///width/1200/crop/630/png/wait/3/?url=(スクリーンショットを撮影したいページのURL)
/auth// → の部分に自分の認証用コード(Key)を指定
/width/1200 → 横幅1200ピクセル
/crop/630 → 高さを630ピクセルで切り抜き
/png → PNG画像
/wait/3 → 撮影まで3秒待機

In this way, by including parameters in the request, you can set specifications such as size and wait time before capturing. While Thum.io does not have many features, you can customize it by following the official documentation to change the parameters.

Installation results

As a result of installing it in this manner and actually running the site,

  • Thum.io was triggered when Facebook or Twitter crawlers accessed ogimage.php, and a screenshot was taken.

  • The captured image was saved to the server.

  • Since the image above functions as a cache, there is no duplicate capturing of the og:image for the same page.

These are the positive results obtained.

The following page does not have an og:image created, but when posted to Twitter, a dynamically generated og:image is displayed.


The quality of the captured og:image is fine; it faithfully reproduces the HTML/CSS coding, and it is generated with web fonts loaded, so I am very satisfied.

Our site has a volume of at most a few hundred pages, so it seems that Thum.io's free tier of 1,000 shots per month will be sufficient. However, if it can take such high-quality screenshots, I felt I would like to consider using it for other purposes beyond just og:image. It is too convenient.

Refresh measures when updating article content

When an article title or a photo in an article is updated, you also want to update the og:image. In that case, if you delete the corresponding article's og:image saved on the server, it will be refreshed the next time a crawler visits.

In the case of WordPress,

function delete_ogimage ($_post_id = null, $_post = null) 
	// 更新された記事IDのog:imageファイルパス
	$file_path = (画像ディレクトリまでの絶対パス) . "$_post_id.png";

	if (file_exists($file_path)) 
		unlink($file_path);
	


add_action('edit_post', 'delete_ogimage', 10, 2);

doing something like this will automatically delete the og:image when the article is updated.

Reference) Mermaid notation for sequence diagrams

The sequence diagram figure I pasted in the text this time was created in Notion using Mermaid notation and captured. Being able to write such detailed diagrams with just this much code without using graphic tools is incredibly convenient...

sequenceDiagram
	autonumber
	participant クローラー

	box DimGray WordPress
		participant ogimage.php
		participant 画像ディレクトリ
		participant ogimage表示用ページ
	end

	box DarkSlateGray thum.io
		participant API
		participant 画像生成エンジン
	end

	クローラー->>ogimage.php: 画像問い合わせ
	ogimage.php->>画像ディレクトリ: 存在チェック

	alt 画像が存在しない場合
		ogimage.php->>API: 画像キャプチャを依頼
		API->>画像生成エンジン: 画像生成を指示
		画像生成エンジン->>ogimage表示用ページ: ページを見に行く
		ogimage表示用ページ->>画像生成エンジン: ページをキャプチャ
		画像生成エンジン->>API: 生成した画像データ
		API->>ogimage.php: 画像データを転送
		ogimage.php->>画像ディレクトリ: 画像を保存
	else 画像が存在する場合
		画像ディレクトリ->>ogimage.php: 画像データを読み込み			
	end

	ogimage.php->>クローラー: 画像を出力

同じカテゴリの記事

雨宮 千夏
デジタルマーケター 雨宮 千夏
プロフィールを見る →

アイドルと音楽シーンの取材を担当。公式サイトの公演情報、リリース告知、公開チャートを照合してから構成しています。

おすすめの関連記事