6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

rails+cloudinaryでOGP画像作成

Last updated at Posted at 2020-04-23

この記事の目的

下記の実装のための知見をまとめてみた

  • OGP画像に可変のテキストを入れたい
  • dynamic URLを使い、加工したい
  • ただし、他のユーザーがURLをいじって画像を大量に作成できないように制限をかけたい
  • transformationをサービスドメインから出ないとできないようにしたい
  • 閲覧には逆に制限をかけたくない(少なくともOGPを取得するであろうtwitterからは見れるように)

cloudinaryの用語解説

dynamic URLとは?

URLを変更することで画像を加工できる機能。今回はogpに記事のタイトルを入れて動的にしたいんだけどこのdynamicurlでテキストをoverlayでいれる。

signed delivery urls

下記のsigneddeliveryurlを使うことでtagで作成しないと画像を生成できないようにする。これで他人に勝手に大量生産される心配がなくなる。

「Signed delivery URLs」
https://cloudinary.com/documentation/control_access_to_media#signed_delivery_urls

railsでOGP生成の全体仕様

全体の流れとしては下記

  • cloudinary_gemの導入
  • cloudinaryのdashboardからcloudinary.ymlを設置
  • metatagsの導入
  • ogptagにcl_image_pathでurlを生成し、いれる

gemの導入

rails導入ドキュメント
https://cloudinary.com//documentation/rails_integration

gem 'cloudinary'

cloudinaly初期設定

cloudinaryのdashboardからcloudinary.ymlを設置

スクリーンショット 2020-04-23 12.53.26.png

ここのymlを落としてconfigディレクトリ内に設置

cloudinary内の設定

  • Strict transformationsをenabledに
  • Restricted media typesにfetchedurlなど対象を

carrierwaveをいれるか

「CarrierWave integration」
https://cloudinary.com/documentation/rails_carrierwave

model経由でuploadしたい場合はcarrierwaveでやると簡単。基本、form_withなどでuploadする場合はこのパターンかなと。今回OGPの生成はすでにuploadずみの画像を加工するのでuploadではない。よって今回はcarrierwave経由ではない。

OGP変換の場合はuploadじゃなくてimageの変換になる

rubyでcloudinaryのurlを生成する場合

  • imgタグごと発行するなら→cl_image_tag
  • urlのみなら→cl_image_path

画像pathの設定

<% set_meta_tags title: "",
description: "",
image: cl_image_path("question_ogp.png",
  :transformation=>[
    {:width=>500, :crop=>"scale"},
    {:width=>470, :overlay=>{:font_family=>"Arial", :font_size=>25, :text=>""}, :crop=>"fit"}
  ],
  :sign_url=>true
)
%>
  • cl_image_pathでurlのみ生成
  • 外側の画像自体の大きさを設定し、内側を470で設定し、その中で文字をcropで折り返されるように設定している

参考資料

gem
https://rubygems.org/gems/cloudinary

cloudinary自身が公式のgemを出してくれている

document
https://cloudinary.com//documentation/rails_integration

「Cloudinary + Rails 画像アップロード」
https://qiita.com/ttexan/items/a1004121e806c477d030

「Rails + Cloudinaryで画像を最適化しよう!」
https://blog.favy.co.jp/8554/

6
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?