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

lufeihaidao · 2013年06月15日 · 最后由 MrTentacle 回复于 2020年02月17日 · 4267 次阅读

背景是这样的:假设存在一张 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 的代码实现。

uudui 回复

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

需要 登录 后方可回复, 如果你还没有账号请 注册新账号