簡體   English   中英

無法使用Rails 5和RMagick gem調整圖像大小

[英]Unable to resize my image using Rails 5 and RMagick gem

我想使用Rails 5應用程序調整上傳圖像的大小以調整其高度(並自動調整寬度)。 我已經安裝了這個寶石

gem 'rmagick'

我正在嘗試像這樣調整大小

@person = Person.new(person_params)
if @person.image

  cur_time_in_ms = DateTime.now.strftime('%Q')
  file_location = "/tmp/file#{cur_time_in_ms}.ext"
  File.binwrite(file_location, @person.image.read)
  file = File.open(file_location, "rb")
  contents = file.read
  # Scale image appropriately
  @person.image = contents.resize_to_fit(1000000, Rails.configuration.max_img_height)

但是在

@person.image = contents.resize_to_fit(1000000, Rails.configuration.max_img_height)

行,我得到錯誤

undefined method `resize_to_fit' for #<String:0x007fab53660c78>

調整圖片大小的正確方法是什么?

您需要先使用RMagick讀取文件:

img = Magick::Image::read(file_location).first

然后可以使用resize_to_fit

@person.image = img.resize_to_fit(75, 75)

這是常見任務的良好指南

當您使用生成新的上傳器時

rails generate uploader Avatar

您會注意到它在uploaders /目錄中添加了一個文件。 內容的開頭看起來像這樣:

class AvatarUploader < CarrierWave::Uploader::Base
  # permissions 0777
  # Include RMagick or MiniMagick support:
  # include CarrierWave::RMagick
  # include CarrierWave::MiniMagick

如果您正在使用rmagick gem,請取消注釋CarrierWave :: RMagick。 否則,取消注釋CarrierWave :: MiniMagick。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM