So I have a collection of thumbnails in my app, which is the size of 200x200. Sometimes the original image doesn\'t have this ratio so I am planning to crop this image
Updated to handle cases where image width is greater than height.
You can do this with pure CSS. Set the container element of each image to have fixed height and width and overflow: hidden
. Then set the image within to have min-width: 100%
, min-height: 100%
. Any extra height or width will overflow the container and be hidden.
HTML
<div class="thumb">
<img src="http://lorempixel.com/400/800" alt="" />
</div>
CSS
.thumb {
display: block;
overflow: hidden;
height: 200px;
width: 200px;
}
.thumb img {
display: block; /* Otherwise it keeps some space around baseline */
min-width: 100%; /* Scale up to fill container width */
min-height: 100%; /* Scale up to fill container height */
-ms-interpolation-mode: bicubic; /* Scaled images look a bit better in IE now */
}
Have a look at http://jsfiddle.net/thefrontender/XZP9U/5/
You can do this easily in CSS if you use background-image.
.thumb {
display: inline-block;
width: 200px;
height: 200px;
margin: 5px;
border: 3px solid #c99;
background-position: center center;
background-size: cover;
}
In this fiddle, first image is 400x800, second image is 800x400:
http://jsfiddle.net/samliew/tx7sf
I came up with my own solution and thought I would share it here in case anyone else found this thread. The background-size: cover solution is the easiest, but I needed something that would work in IE7 as well. Here's what I came up with using jQuery and CSS.
Note: My images were "profile" images and needed to be cropped to squares. Hence some of the function names.
jQuery:
cropProfileImage = function(pic){
var h = $(pic).height(),
w = $(pic).width();
if($(pic).parent('.profile-image-wrap').length === 0){
// wrap the image in a "cropping" div
$(pic).wrap('<div class="profile-image-wrap"></div>');
}
if(h > w ){
// pic is portrait
$(pic).addClass('portrait');
var m = -(((h/w) * 100)-100)/2; //math the negative margin
$(pic).css('margin-top', m + '%');
}else if(w > h){
// pic is landscape
$(pic).addClass('landscape');
var m = -(((w/h) * 100)-100)/2; //math the negative margin
$(pic).css('margin-left', m + '%');
}else {
// pic is square
$(pic).addClass('square');
}
}
// Call the function for the images you want to crop
cropProfileImage('img.profile-image');
CSS
.profile-image { visibility: hidden; } /* prevent a flash of giant image before the image is wrapped by jQuery */
.profile-image-wrap {
/* whatever the dimensions you want the "cropped" image to be */
height: 8em;
width: 8em;
overflow: hidden;
}
.profile-image-wrap img.square {
visibility: visible;
width: 100%;
}
.profile-image-wrap img.portrait {
visibility: visible;
width: 100%;
height: auto;
}
.profile-image-wrap img.landscape {
visibility: visible;
height: 100%;
width: auto;
}