How do I resize an existing image to, say “260×180?”
I am using Carrierwave and Rmagick currently to upload images to my Amazon S3 storage bucket, and it creates 2 versions of the image: the original, and the thumb version( 70×70).
Now, I know that I can create another version so that three versions would be created, including the 260×180, but I felt like that was over-clogging the storage database, and I was wondering if I could do it on a view level.
I tried
<%= image_tag(@syllabus.image_url, :size => "260x180") %>
but it seems like it’s not working – the images are not identical sizes.
Also, if the image is smaller than my desired output, do I need to do something different than to images that are bigger? For example, do I need to cut the bigger ones, but expand the smaller ones, or will it automatically scale to the desired size?
Like @Yosep said, there’s nothing magical of rails going on here.
<%= image_tag %>generates an<img>tag in the result html. if you pass a:size => '260x180', the result<img>tag will have itswidthandheightset to 260 and 180.Here comes the answer for your question. the best way of providing another image size, is the way you turned down at the beginning. You need to resize those images in the backend and store them somewhere.
Resizing image by setting the width and height of
<img>tag will not keep the image’s original aspect ratio. if the original ratio is 260:180, then it’s fine. But if not, the result will be ugly. Besides, there’s another drawback of doing so, which is the same reason that you should not resize image using CSS also. Resizing large images into smaller ones at client side will eventually be a huge waste of your network, and doing so will slow your site’s rendering. That’s one of YSlow’s rules.To resize image using CSS, you can use
max-widthandmax-height, larger images will be resized accordingly, smaller ones will not be resized.