少於 1 分鐘閱讀

預安裝

須先安裝 ImageMagick 或是 GraphicsMagick command-line tool (這邊以 ImageMagick 為例)

Linux

$ sudo apt-get install imagemagick  

Mac

$ brew install imagemagick

確認是否安裝成功

$ convert -version
Version: ImageMagick 6.8.9-7 Q16 x86_64 2014-09-11 http://www.imagemagick.org
Copyright: Copyright (C) 1999-2014 ImageMagick Studio LLC
Features: DPC Modules
Delegates: bzlib fftw freetype jng jpeg lcms ltdl lzma png tiff xml zlib

安裝

gem "mini_magick"

直接抓網路上的圖片來處理

uri = open("http://your.path.com/yourpic.jpg")
img = MiniMagick::Image.new(uri.path)

衍伸問題: 如遇到 redirection 的問題,可安裝 open_uri_redirections 這個 gem 並把寫法改為 open("http://your.path.com/yourpic.jpg", allow_redirections: :safe)

增加文字

img.combine_options do |c|
  c.gravity 'NorthWest'
  c.pointsize '14'
  c.draw "text 0,0 'hello world'"
  c.fill 'blue'
end

疊加圖片

把 current_img 放到 background_img 的座標 20, 20 的位置

background_img = MiniMagick::Image.new(background_img_path)
current_img = MiniMagick::Image.new(current_img_path)

background_img = background_img.composite(current_img) do |c|
  c.compose "Over"
  c.geometry "+20+20" #座標
end

參考

  1. https://github.com/minimagick/minimagick
  2. https://ruby-china.org/topics/3268
  3. https://ruby-china.org/topics/5673
  4. https://github.com/open-uri-redirections/open_uri_redirections
  5. https://gist.github.com/seyhunak/6495608
  6. https://gist.github.com/elvuel/4057324

更新時間:

留言