-3

我在我的模型中创建了一个函数来确定图像的尺寸和偏移量,当缩放以适应载波的特定尺寸时:

def get_auto_crop_dims(original_width, original_height, cropped_width, cropped_height)
  auto_dims = {:scale_width => 0, :scale_height => 0, :offset_x => 0, :offset_y => 0}

  # IF original image is the SAME orientation as container ie. portrait vs. portrait THEN image largest dimension = 100%
  # IF original image is the DIFFERENT orientation as container ie. portrait vs. landscape THEN image smallest dimension = 100%

  if ((cropped_height >= cropped_width and original_height >= original_width) or (cropped_height >= cropped_width and original_height <= original_width))
    # height 100%
    auto_dims[:scale_height] = cropped_height
    auto_dims[:scale_width] = (auto_dims[:scale_height]/original_height)*original_width
    auto_dims[:offset_y] = 0
    auto_dims[:offset_x] = (auto_dims[:scale_width]-cropped_width)/2
  else 
    # width 100%
    auto_dims[:scale_width] = cropped_width
    auto_dims[:scale_height] = (auto_dims[:scale_width]/original_width)*original_height
    auto_dims[:offset_x] = 0
    auto_dims[:offset_y] = (auto_dims[:scale_height]-cropped_height)/2
  end

  return auto_dims

end 

它被称为:

dims[:title][:width], dims[:title][:height] = `identify -format "%wx%h" #{image.title.file.path}`.split(/x/)
    dims[:title].merge!(get_auto_crop_dims(dims[:original][:width].to_i, dims[:original][:height].to_i, dims[:title][:width].to_i, dims[:title][:height].to_i))

self.dimensions = dims.to_json

上传图片后,返回的结果是:

> PageImage.last.dimensions
  PageImage Load (0.8ms)  SELECT `page_images`.* FROM `page_images` ORDER BY `page_images`.`id` DESC LIMIT 1
 => "{\"original\":{\"width\":\"1600\",\"height\":\"1200\\n\"},\"title\":{\"width\":\"960\",\"height\":\"384\\n\",\"scale_width\":960,\"scale_height\":0,\"offset_x\":0,\"offset_y\":-192},\"thumb\":{\"width\":\"220\",\"height\":\"130\\n\",\"scale_width\":220,\"scale_height\":0,\"offset_x\":0,\"offset_y\":-65}" 

问题是:

dims[:title][:scale_width] = 0 

意味着存在某种问题:

auto_dims[:scale_height] = (auto_dims[:scale_width]/original_width)*original_height 

我无法理解为:

:scale_width = 960 & original_width = 1600 & original_height = 1200 

为什么没有dims[:title][:scale_width] = 720?。

4

1 回答 1

3

当您在 Ruby 中除整数时,它们也不会像您期望的那样除以小数。例如:

  • 9 / 4= 2
  • 4 / 9= 0

您在图中看到的4 / 9是当您将比例宽度除以原始宽度时发生的情况,这是一个更大的数字。要获得您希望的小数,其中一个操作数必须是浮点数(例如4.0 / 9= 0.444...)。因此,您可以将代码更改为:

auto_dims[:scale_height] = (auto_dims[:scale_width].to_f/original_width)*original_height

to_f调用只是将其中一个操作数更改为浮点数。

于 2013-07-23T14:27:55.063 回答