32
22

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】CarrierWaveとMiniMagickで画像を.wepbに変換する

Last updated at Posted at 2023-09-25

画像を.webpに変換したい

と思って記事を探したんですが、無さそうだったので投稿します。

CarrierWaveとMiniMagickの導入方法については多くの記事があるため、今回は割愛させて頂きます。

.webpに変換する方法

具体的な方法ですが、CarrierWaveのUploaderクラスに記載するだけです。

$ rails generate uploader 〇〇〇コマンドで作られたファイルにコードを書きます。🔥マークのコメントが該当部分

app/uploaders/stamp_image_uploader.rb
class BoozeImageUploader < CarrierWave::Uploader::Base
  # Include RMagick or MiniMagick support:
  # include CarrierWave::RMagick
  include CarrierWave::MiniMagick  #🔥CarrierWaveでMiniMagickが使えるようにする

  # Choose what kind of storage to use for this uploader:
  # storage :file
  # productionでは、fogで外部ストレージにアップロードする
  if Rails.env.development? || Rails.env.test?
    storage :file
  else
    storage :fog
  end

  # Override the directory where uploaded files will be stored.
  # This is a sensible default for uploaders that are meant to be mounted:
  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

  # Provide a default URL as a default if there hasn't been a file uploaded:
  def default_url
    'no_image_gray.png'
  end

  # Process files as they are uploaded: 
  process resize_to_fit: [1000, 667]

  # def scale(width, height)
  #   # do something
  # end

  # Create different versions of your uploaded files:
  # version :thumb do
  #   process resize_to_fit: [50, 50]
  # end

  # Add an allowlist of extensions which are allowed to be uploaded.
  # For images you might use something like this:
  def extension_allowlist
    %w[jpg jpeg gif png heic webp]
  end

  # Override the filename of the uploaded files:
  # Avoid using model.id or version_name here, see uploader/store.rb for details.

  #🔥WebPに変換
  process :convert_to_webp

  def convert_to_webp
    manipulate! do |img|
      img.format 'webp'
      img
    end
  end
    #🔥拡張子を.webpで保存
  def filename
    super.chomp(File.extname(super)) + '.webp' if original_filename.present?
  end

1 オリジナル WebP
5472x3648px 3.0 MB 2.1 MB
1000x667 px 302.7 KB 207.0 KB

横幅500pxにしてるので分かりづらいでずが、画質の差にもそれほど違いがないことがわかります。
ただ、WebPに変換するだけでは10~30%程度の圧縮にしかならないので、画像のリサイズは必須かなと思います。

WEBページであれば横幅1000pxあれば充分なようです。

最後になりましたが、うぇぶぴーじゃなくてウェッピーって読むのかわいいです。

32
22
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
32
22

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?