CloudinaryでOGP画像を自動生成する
Cloudinaryとは
Cloudinaryは画像や映像、メディアを簡単に配信できるストレージサービス。URLを入力するだけや多くのAPIで画像の編集などがすぐに行える。無料枠も存在する。
テキストを表示する
https://cloudinary.com/documentation/image_transformations#using_custom_fonts_for_text_overlays アップロードした画像に対してテキストを表示することができる。 URLで使用すると以下のようなURLになる。
https://res.cloudinary.com/demo/image/upload/w_500/l_text:Verdana_75_bold_underline_letter_spacing_14:Flowers/flowers.jpg
大体以下のような構造になっている。
const baseUrl = \"\"; const font = \"Verdana\"; const fontSize = \"75\"; const fontStyle = \"bold\"; const text = \"Hoge\"; const image = \"sample.jpg\"; const options = \"w_800,c_fit\"; const url = `${baseUrl}/${options}l_text:${font}_${fontSize}_${fontStyle}:${text}/${image}`;
w_XXX
は文字の最大の幅がXXX
ピクセルとなるように設定する。
c_fit
は文字が最大の幅に到達したときに折り返す。スペースの内英字だと折り返されずに...
となる。
カスタムフォントを使う
カスタムフォントを使おうとしたら若干手間取った。フォントを使えるようにアップロードするには以下のようにいくつかの設定をする必要がある。
Cloudinary::Uploader.upload(\"AlexBrush-Regular.ttf\", resource_type: 'raw', # Custom fonts must be upload as 'raw' type: 'authenticated', # Custom fonts must be upload as 'authenticated' public_id: 'AlexBrush-Regular.ttf')
この設定はブラウザが適用するには設定画面から設定を作る必要がある。 https://support.cloudinary.com/hc/en-us/community/posts/360048769011-Custom-font
Signing ModeをSignedに、Delivery typeをAuthenticatedに設定する。 画像やビデオ以外のrawに対してこの設定を適用してフォントをブラウザからアップロードすれば使えるようになる。