LoginSignup
2
1

More than 5 years have passed since last update.

CarrierWaveで元画像のサイズ(高幅x横幅)を取得する

Posted at

20161212123706.png

やりたいこと

CarrierwaveでS3にアップロードした画像のサイズを取得できるようにしたい

シチュエーション

  • resize_to_limit を使っている。

  • AMP対応につきリサイズされた画像のサイズを正確に知っておきたい。

  • 画像はS3上にある

  • S3にリクエスト投げて画像サイズを取得するのはまじで嫌だ(例: MiniMagick::Image.open(article.image_url)[:dimensions])

解決法

app/uploaders/thumb_uploader.rb

def filename
  "#{secure_token}.#{file.extension}" if original_filename.present?
end

def dimensions
  path.scan(/\d+x\d+/).to_s.scan(/\d+/)
end

protected

def secure_token
  var = :"@#{mounted_as}_secure_token"
  return model.instance_variable_get(var) if model.instance_variable_get(var)
  width, height = ::MiniMagick::Image.open(file.file)[:dimensions]
  size_with_random = "#{width}x#{height}_#{SecureRandom.uuid}" 
  model.instance_variable_set(var, size_with_random)
end

解説

  1. 画像保存時にファイル名を<横幅>x<縦幅>_<ランダム>.<拡張子>と言うフォーマットにする。

  2. ファイル名からサイズを取得(Article#thumb#dimensions)

2
1
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
2
1