15
14

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 5 years have passed since last update.

何回やってもRailsで画像のリサイズができない

Last updated at Posted at 2018-08-11

###実現したいこと
gem Cariierwave を使ってuploadした画像を
gem 'mini_magick' を 使ってリサイズ。

###試したサイト一覧
MacのHomebrewでimagemagickを入れているとgem install rmagickが失敗するようになったメモ
【162日目】【1日20分のRailsチュートリアル】【第11章】アップロード時に画像のリサイズを実施する
Rails5とCarrierWaveを使って画像アップロード機能を作る
brewでimagemagickをupgradeしてしまい、rmagickでエラーが出る場合
Rails5.1「carrierwave」で画像をアップロード
RubyのRMagickで画像をリサイズする
CarrierWave + RMagick 画像のリサイズをまとめてみました
Railsでcarrierwaveのgemを使った画像表示をしたいです!
rails5でのcarrierwaveを用いた画像投稿機能の実装でのエラー
Rails5の画像リサイズについて
Rails CarrierWaveで画像をリサイズする
rmagickを使って画像をリサイズする
RMagickが cannot load such file -- rmagick でロードできない
Carrierwaveで画像をリサイズする
・・当然ながら下から順に全て試した上で、画像のリサイズは何回やっても出来ません。記事の新旧・Rails verの相違を踏まえた上で検索し直しても上手くいかないとは一体どういうことなのか

###gemを使ってダメならcssで指定してみれば・・?

<p id = "class">
  <strong>Image:</strong>
  <%= image_tag(@item.image.to_s) %>
</p>
#class {
height:400px;
width:400px;
}

pタグ自体の指定を試す、あるいは

<%= imgage_tag(@image.image.to_s), :size => 200×200 %>

イメージタグ内にサイズ指定を宣言すれば上手くいくかと思いきや、
cssの方では、投稿画像がp#imageになっている為pタグにcssを指定する形では適用されず、:sizeではエラーが起きるか無視されるかで両方とも失敗

###成功例

show.html.erb
<p>
  <strong>Image:</strong>
  <%= image_tag(@item.image.to_s) %>
</p>
#item.rb
class Item < ApplicationRecord
		mount_uploader :image, ImagesUploader
end
#images.uploader.rb
class ImagesUploader < CarrierWave::Uploader::Base
  include CarrierWave::MiniMagick
  process resize_to_limit: [400, 400]

  storage :file

  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

  def extension_white_list
    %w(jpg jpeg gif png)
  end
end
_form.html.erb
<div class="field">
    <%= form.label :image_path %>
    <%= form.file_field :image, id: :items_image_path %>
  </div>
#items.controller.rb
def create
    @item = Item.new(item_params)
    if params[:img] != nil
       img = MiniMagick::Image.read(params[:img])
       img.resize "300x300"
       img.write "public/images/hoge.jpg"
    end

    respond_to do |format|
      if @item.save
        format.html { redirect_to @item, notice: 'Item was successfully created.' }
        format.json { render :show, status: :created, location: @item }
      else
        format.html { render :new }
        format.json { render json: @item.errors, status: :unprocessable_entity }
      end
    end
  end

items.controllerとimages.uploaderでリサイズの設定が被っている挙句、
投稿した画像サイズは400×255にリサイズされているなど散々な結果ではあるが、
これ以外では何を試しても数時間以上に及んでリサイズされなかった画像が
初めてリサイズ可能になったので諦めた。
Railsチュートリアルのリサイズも試してみましたが、あのチュートリアルにある内容何を試しても成功しないのは仕様なのだろうか・・

###画像を400×400にリサイズすることは可能なのか
Using Rmagick to resize height firstより

Example: img.resize_to_fit(300). Depending on your picture you get a picture with maximum width 300 or length 300. The other dimension is calculated by the ratio. A 50x100 picture becomes 150x300. A 100x50 picture becomes 300x150.

If you want a 300x400 picture you can't use img.resize_to_fit(300,400), it would check, which dimension does fit first and calculate the other dimension depending on it.

If your prefer height over width means, that you want a given height (e.g. 300) and the width should be calculated by the picture ratio, you may use resize_to_fit(1000000, 300). Every times the height 300 will be reached before the width 1000000 is reached, your picture will get the height 300.

とあり、引数に入れる(300,300)は300×300にリサイズするという意味ではなく、横幅or縦幅が先に指定値を満たすか判断した後で、それに見合ったratio(比率)をもう片方の幅に対して算出するとのこと。

僕のケースの場合は他の画像が128*128サイズであったので、はじめに

#images.uploader.rb
  include CarrierWave::RMagick #MinimagickをRmagickに変更
 process resize_to_fir(10000,128)

を試したところ128*75が帰ってきたので、リンク先質問にもあった、高さを横幅よりも先に指定したい方法が上手くいかなかったので

#images.uploader.rb
  include CarrierWave::RMagick #MinimagickをRmagickに変更
 process resize_to_fit(128)

を試したところ、228*128が帰ってきたので、少なくとも高さの指定は通ったので他の画像に比べて横幅が長くなる違和感が未だ消えないがひとまず解決。

###遂に解決

#items.controller.rb
def create
    @item = Item.new(item_params)
    if params[:img] != nil
       img = MiniMagick::Image.read(params[:img])
       img.resize_to_fill "128x128" #resizeをresize_to_fillに変更
       img.write "public/images/hoge.jpg"
    end

もともと二つ画像のリサイズを行う設定を行っていたので、images.uploaderの方ではなく、画像を投稿する画面はmodel Item内なので、def createのメソッドの記述を変更すればいいと気づく。
するとようやく画像が念願の128*128サイズに!!!
railsの繋がりがpaizaやdotinstall学習を終えた後でもさっぱり分かってない状況では、そもそもどこを変えたら何に繋がるのかがイメージ出来ていないことによる失態かと思われる。

気づきのキッカケになった参考サイト
第26回 RMagickを用いた画像処理(1)リサイズ

15
14
1

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
15
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?