Ruby on Rails 2.1 - RMagick 指南



Rails 提供了與ImageMagickGraphicsMagick 的繫結,它們是流行且穩定的 C 庫。RMagick 庫針對 ImageMagick 和 GraphicsMagick 提供相同的介面,因此使用哪個庫都沒有關係。

您可以透過在 Unix 上安裝 rmagick gem 或在 Windows 上安裝 rmagick-win32 gem 來獲得RMagick。讓我們按照以下步驟在 Unix 機器上安裝它:

$ gem install rmagick

RMagick 模組附帶了Magick::Image 類,它允許您透過四種不同的方法調整影像大小:

  • resize(寬度, 高度)
  • scale(寬度, 高度)
  • sample(寬度, 高度)
  • thumbnail(寬度, 高度)

所有這些方法都接受一對整數值,分別對應於所需縮圖的畫素寬度和高度。

示例

這是一個使用resize() 方法調整影像大小的示例。它獲取檔案tmp.jpg 並將其縮圖的大小調整為 100 畫素寬,100 畫素高:

require 'rubygems'
require 'RMagick'

class ImageController < ApplicationController

   def createThubnail
      width, height = 100, 100

      img =  Magick::Image.read('tmp.jpg').first
      thumb = img.resize(width, height)
	   
      # If you want to save this image use following
      # thumb.write("mythumbnail.jpg")

      # otherwise send it to the browser as follows
      send_data(thumb.to_blob, :disposition => 'inline', :type => 'image/jpg')
   end
end

建立縮圖的步驟如下:

  • 這裡,類方法Image.read接收影像檔名作為引數並返回一個 Image 物件陣列。您獲取該陣列的第一個元素,顯然是我們的tmp.jpg影像。

  • 接下來,我們使用所需引數呼叫resize方法,從而建立縮圖。

  • 最後,我們將此影像定向到瀏覽器。您也可以使用thumb.write("mythumbnail.jpg") 方法將此影像儲存在您的本地機器上。

轉換影像格式

將影像檔案從一種格式轉換為另一種格式非常容易。RMagick 可以巧妙地處理它。您只需讀取檔案並使用不同的副檔名將其寫入即可。

示例

以下示例將 JPEG 檔案轉換為 GIF 檔案:

require 'rubygems'
require 'RMagick'

class ImageController < ApplicationController

   def changeFormat

      img =  Magick::Image.read('tmp.jpg').first
    
      # If you want to save this image use following
      # img.write("mythumbnail.gif")

      # otherwise send it to the browser as follows
      send_data(img.to_blob, :disposition => 'inline', :type => 'image/gif')
   end
end

您可以根據需要將影像更改為以下格式:

img = Magick::Image.read("tmp.png").first
img.write("tmp.jpg")                 # Converts into JPEG
img.write("tmp.gif")                 # Converts into GIF
img.write("JPG:tmp")                 # Converts into JPEG
img.write("GIF:tmp")                 # Converts into GIF
廣告
© . All rights reserved.