【问题标题】:Resize not working with Shrine and ImageProcessor / MiniMagick - Rails 5.2调整大小不适用于 Shrine 和 ImageProcessor / MiniMagick - Rails 5.2
【发布时间】:2021-04-09 17:37:13
【问题描述】:

我正在尝试使用 ImageProcessor / MiniMagick 来调整图像大小,然后再将它们保存到我的 Rails 5.2 应用程序的数据库中。我可以保存图像,但是在保存之前未调整此图像的大小,并且没有引发错误。我也在使用 Trix 来处理和输出图像。

这是我目前设置的:

image_uploader.rb

require "image_processing/mini_magick"

class ImageUploader < Shrine
  Attacher.derivatives do |original|
    magick = ImageProcessing::MiniMagick.source(original)
      {
        resized: magick.resize_to_limit!(600, 600)
      }
  end
end

shrine.rb(我在shrine.rb 文件中包含以下行)

Shrine.plugin :derivatives

photos_controller.rb(photos_controller.rb 文件中的相关代码)

def create
    @photo = Photo.new(photo_params)
    @photo.valid?
    @photo.image_derivatives! if @photo.image_changed? # creates derivatives
    
    respond_to do |format|
      if @photo.save
        format.html { redirect_to @photo, notice: 'Photo was successfully created.' }
        format.json { render :show, status: :created, location: @photo }
      else
        format.html { render :new }
        format.json { render json: @photo.errors, status: :unprocessable_entity }
      end
    end
  end

代码似乎与我在数据库中看到的一样有效。控制台日志如下所示:

2.6.1 :014 > photo.image_derivatives
 => {:resized=>#<ImageUploader::UploadedFile storage=:store id="b234085e9502c39f23edb84bced89ee0.png" metadata={"filename"=>"image_processing20210103-23514-zyeyzg.png", "size"=>94105, "mime_type"=>"image/png"}>} 
2.6.1 :015 > photo.image(:resized)
 => #<ImageUploader::UploadedFile storage=:store id="b234085e9502c39f23edb84bced89ee0.png" metadata={"filename"=>"image_processing20210103-23514-zyeyzg.png", "size"=>94105, "mime_type"=>"image/png"}> 
2.6.1 :017 > photo.image(:resized).size
 => 94105 
2.6.1 :018 > photo.image(:resized).mime_type
 => "image/png" 

当我拉出保存的记录时,我可以找到让我认为它有效的信息,但是当我在视图中查看它时没有调整大小。有什么想法吗? ...如果我应该提供更多信息,请告诉我。

【问题讨论】:

  • 是否需要在视图中以不同方式调用更改后的图像?
  • 如果您调用@photo.image(:resized),调整大小确实有效,但是我不确定如何显示通过 'reading.body' 和 trix 输出的图像。

标签: ruby-on-rails image-processing minimagick shrine


【解决方案1】:

虽然这不是我正在寻找的答案,但处理此问题的一种方法是通过 css。我将以下内容添加到我的 css 文件中,效果很好。文件保存在后端的方式没有任何改变,但浏览器中的外观是我正在寻找的:

.trix-content {
  img {
    max-width: 400px;
  }
}

【讨论】:

    猜你喜欢
    • 2012-09-10
    • 1970-01-01
    • 2011-12-08
    • 2019-01-24
    • 2014-09-04
    • 1970-01-01
    • 2021-03-24
    • 2013-11-25
    • 2013-08-09
    相关资源
    最近更新 更多