我在我的模型中创建了一个函数来确定图像的尺寸和偏移量,当缩放以适应载波的特定尺寸时:
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
?。