Rails Rails 的 controller 中如何处理图片路径?

lufeihaidao · June 15, 2013 · Last by MrTentacle replied at February 17, 2020 · 4268 hits

背景是这样的:假设存在一张 200*200 的纯白图片(可以在 public 文件夹下,也可以在 app/asset/images 文件夹下),在某个 controller 的方法中,需要用 mini_magick 读取这个文件,并根据用户的输入(比如 (line 0,0,100,100) 就是画出一条 (0,0) 到 (100,100) 的连线),生成一幅图片,并保存。

但是,在 controller 里不能用 views 里常用的 image_path 之类的方法,怎样得到图片的正确路径并正确保存呢?

class HomeController < ApplicationController
  def show
    image = MiniMagick::Image.open( get_image_path "sample.jpg" )
    image.draw "line 0,0,100,100"
    image.save( to_the_asset_path "test1.jpg")
  end
end

代码的样子大概是这样的,请问怎样在 controller 里访问图片?

"#{Rails.root}/path/to/image"

如果要用也可以 inclue 进来,不过不赞成这么干。

直接看 image_path 的代码实现。

Reply to uudui

感谢提醒 我照抄了部分源码.... 在 serializer 的子类中读取到了 app/aseets/images/img 中的图片路径 😂

You need to Sign in before reply, if you don't have an account, please Sign up first.