Crop your images with CSS!


Instead of tracking down your language’s fancy image libraries, you can crop images very quickly with css.
Simply use negative absolute positioning!
HTML:

<div class="crop">
    <img src="https://www.google.com/images/srpr/logo3w.png" alt="" />
</div>

CSS:

.crop  {
    height: desiredImageHeight;
    width: desiredImageWidth;
    overflow: hidden;
    position: relative;
}
.crop img{
    position: absolute;
    top: -pixelsToRemoveFromTop;
    left: -pixelsToRemoveFromLeft;
}

If you don’t know the size of the image beforehand, you can use some javascript to compute the height and width:

// Assumes img is inside a div with same width and height and overflow: hidden
function centerCrop(img, width, height) {
    function repositionImgHelper() {
        var top = (this.height - height)/2;
        var left = (this.width - width)/2;
        if ( top > 0 ) {
            img.css('top', -top+'px');
        }
        if (left > 0) {
            img.css('left', -left+'px');
        }
        return true;
    }
    function repositionImg(imgPath) {
        var myImage = new Image();
        myImage.name = imgPath;
        myImage.onload = repositionImgHelper;
        myImage.src = imgPath;
    }
    repositionImg(img.attr('src'));
}
$(function () {
    var jqueryImageObject = $('.crop img');
    centerCrop(jqueryImageObject, desiredWidth, desiredHeight);
});

Leave a comment

Your email address will not be published. Required fields are marked *