2010-07-12 25 views
5

我試圖用Rmagick調整圖像大小,如果我用resize_to_fit方法總是先調整高度,寧願,要寬,但它好像我的大部分圖片都被調整到寬度第一。無論如何,使用resize_to_fit方法來告訴它「喜歡高度超過寬度」?使用Rmagick來調整高度的第一

回答

3

一些想法和一些代碼。

你看到了什麼差異?你怎麼能先告訴它的寬度?我沒有看到最終結果應該是不同的大小的情況,如果這是一個例子可能會有幫助的質量問題。

它看起來並不像該API的方式來舒展的一種方式,然後另一個但我們一定可以讓一個或兩個的方法來試一試。有兩種方法,第一種,two_step_resize調整大小在一個方向和另一個。第二個,resize_with_rotate旋轉圖像,調整大小,然後將其旋轉回來。

爲例子我跑它通過我沒有看到任何一個解決方案的任何奇怪。

require 'RMagick' 


#Change the size in two steps, height first then width 
def two_step_resize(img, filename, max_x, max_y) 
    x = img.columns 
    y = img.rows 

    #make sure it's a float w/ the 1.0* 
    ratio = (1.0*x)/y 

    new_y = max_y 
    new_x = ratio * new_y 

    if (new_x > max_x) 
    new_x = max_x 
    new_y = new_x/ratio 
    end 

    # do the change in two steps, first the height 
    img.resize!(x, new_y); 
    #then the width 
    img.resize!(new_x, new_y) 

    #save it, with the least compression to get a better image 
    res.write(filename){self.quality=100} 

end 

#spin the image before resizing 
def resize_with_rotate(img, output_filename, max_x, max_y) 
    res = img.rotate(90).resize_to_fit(max_y, max_x).rotate(-90) 
    res.write(output_filename){self.quality=100} 
end 

img = Magick::Image.read(filename).first 
two_step_resize(img, "2-step.jpg", 100, 200) 

img = Magick::Image.read(filename).first 
resize_with_rotate(img, "rotate.jpg", 100, 200) 
+0

實際上,我發現最好的解決方案是使用resize_to_fill!裁剪圖像以獲得我想要的尺寸。我不明白,它的寬度或高度無關緊要,無論哪一個更大,都是我縮放的數字,因爲它會保持寬高比。不過,我會給你答案的要點。 – tesserakt 2010-07-20 14:09:03

12

我不明白你的意思來調整高度的第一什麼。所以也許我錯了我的答案。

當你調整,你有三種可能性:(?scale)你可以保持比(resize_to_fit)或裁剪圖片(resize_to_fill)或伸展/收縮圖片

隨着resize_to_fit你可以定義一個最大寬度和可選最大長度(默認爲給定寬度)。

實施例:img.resize_to_fit(300)。根據您的圖片,您可以獲得最大寬度爲300或長度爲300的圖片。其他尺寸按照比例計算。 50x100圖片變爲150x300。 100x50圖片變爲300x150。

如果你想有一個300x400的圖片,你不能使用img.resize_to_fit(300,400),它會檢查,其尺寸倒是第一次,並計算依賴它的其他維度。

如果您的偏好高度超過寬度意味着您想要給定高度(例如300)並且寬度應該由圖片比例計算,您可以使用resize_to_fit(1000000, 300)。 每一個時代的高度300將達到達到寬度百萬之前,你的畫面會得到高度300

+0

最佳總結我已經看到了!謝謝。 – 2014-12-03 17:25:04

1

您可以指定高度最大值,讓Rmagick使用change_geometry方法計算出相應的寬度。

這可以在案件有用,你要設置的景觀圖像的最大高度,並且不希望指定相應的寬度保留率:

require "rmagick" 
include Magick 

img = ImageList.new("<path_to_your_img>") # assuming a landscape oriented img 
img.change_geometry("x395") do |cols, rows, img| # set the max height 
    img.resize(cols, rows) 
end 

千萬記得你總是必須通過阻止改變幾何方法。 你可以找到官方documentation的更多信息。

乾杯