我正在尝试使用Rmagick调整图像大小,如果我使用该resize_to_fit方法始终首先调整高度,则优先选择宽度,但似乎我的大多数图像都首先调整为宽度.无论如何使用该resize_to_fit方法告诉它"更喜欢高度超过宽度"?
knu*_*nut 12
我不明白你的意思是先调整高度.所以也许我的回答是错的.
调整大小时有三种可能性:您可以保持比例(resize_to_fit)或裁剪图片(resize_to_fill)或拉伸/缩小图片(scale?)
与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).在达到宽度1000000之前,每次达到高度300,您的图片将达到300的高度.
一些想法和一些代码。
您看到什么差异?你怎么能先知道它的宽度?我没有看到最终结果应该有不同尺寸的情况,如果是质量问题,一个例子可能会有所帮助。
看起来 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)
Run Code Online (Sandbox Code Playgroud)
        |   归档时间:  |  
           
  |  
        
|   查看次数:  |  
           2975 次  |  
        
|   最近记录:  |