Reputation: 6897
In my Rails 4 app, I use the MetaInspector gem to scrap images from a link provided by the user.
This way, I am capable of doing something like this in my views:
<%= image_tag(@link.images.best) %>
and it works pretty well.
Now, I would like to resize / crop these images to a particular dimension of 450x246px so, I tried to do this:
<%= image_tag(@link.images.best, size: "450x246") %>
but this solution does not preserve the initial ratio of the images.
I am fine with "cutting" the images as long as we do not distort them.
I found this solution but it does not fit my use case: I do not want to store the images in my database, I simply want to pull them from a URL and display them in my views.
How can I resize / crop my images "on the fly" directly in my views?
Upvotes: 0
Views: 1389
Reputation: 6897
Here is what I ended up doing:
#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;
}
This works really well, no matter the width or the height of the original image.
Upvotes: 1
Reputation: 1452
I would like to resize / crop these images to a particular dimension of 450x246px
You can fit an image within a space of that dimension by setting the max-width
or the max-height
css property of the image, whichever option fits better your use case.
<%= image_tag(@link.images.best, style: "max-width: 450px") %>
or
<%= image_tag(@link.images.best, style: "max-height: 246px") %>
And if you so desire the image size to be exactly your specified dimensions, you will have to crop large images and expand smaller images (while maintaining aspect ratio of course) in which case you have multiple ways to do that, all of which have already been answered here.
Upvotes: 2