Rails 4:从 URL 裁剪图像并保持比例

Rails 4: crop image from URL and preserve ratio

在我的 Rails 4 应用程序中,我使用 MetaInspector gem 从用户提供的 link 中抓取图像。

这样,在我看来,我有能力做这样的事情:

<%= image_tag(@link.images.best) %>

而且效果很好。

现在,我想将这些图像调整大小/裁剪到 450x246 像素的特定尺寸,所以,我尝试这样做:

<%= image_tag(@link.images.best, size: "450x246") %>

但此解决方案不会保留图像的初始比例。

我对 "cutting" 图片没意见,只要我们不扭曲它们。

我找到了 this solution 但它不适合我的用例:我不想将图像存储在我的数据库中,我只是想从 URL 中提取它们并将它们显示在我的看法。

如何直接在我的视图中调整/裁剪图像 "on the fly"?

I would like to resize / crop these images to a particular dimension of 450x246px

您可以通过设置图像的 max-widthmax-height css 属性 使图像适合该尺寸的 space,以哪个为准选项更适合您的用例。

<%= image_tag(@link.images.best, style: "max-width: 450px") %>

<%= image_tag(@link.images.best, style: "max-height: 246px") %>

如果您希望图像大小正好是您指定的尺寸,您将不得不裁剪大图像并扩展较小图像(当然同时保持纵横比),在这种情况下,您有多种方法可以做到这一点,所有这些都已经 answered here.

这是我最后做的事情:

#HTML
<div id="container" style="background-image:url(<%= @link.images.best %>);">
</div>

#CSS
#container {
    overflow: hidden;
    width: 445px;
    height: 246px;
    background-position: 50% 50%;
    background-repeat: no-repeat;
    background-size: cover;
    background-color: transparent;
}

无论原始图像的宽度或高度如何,这都非常有效。