CSS缩放和正方形中心裁剪图像

CSS scale and square center crop image

本文关键字:裁剪 图像 正方形 缩放 CSS      更新时间:2023-09-26

我的应用程序中有一个缩略图集合,大小为200x200。有时原始图像没有这个比例,所以我计划将图像裁剪为正方形。

目前它只是拉伸图像以适应缩略图,所以说我的原始图像大小是400x800,然后图像看起来非常压缩。我想裁剪这张图片,让它看起来是最短的宽度/高度,然后裁剪成一个正方形,所以在上面的例子中,它将被裁剪为400x400

是否有一种方法可以通过CSS轻松做到这一点,或者我必须使用某种JS来做到这一点?

在CSS中使用background-image可以很容易地做到这一点。

.thumb {
    display: inline-block;
    width: 200px;
    height: 200px;
    margin: 5px;
    border: 3px solid #c99;
    background-position: center center;
    background-size: cover;
}

在这里,第一张图片是400x800,第二张图片是800x400:

http://jsfiddle.net/samliew/tx7sf

更新以处理图像宽度大于高度的情况。

你可以用纯CSS做到这一点。设置每个图像的容器元素具有固定的高度和宽度和overflow: hidden。然后将图像设置为min-width: 100%, min-height: 100%。任何额外的高度或宽度都会溢出容器并被隐藏。

<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 */
}

看看http://jsfiddle.net/thefrontender/XZP9U/5/

我想出了我自己的解决方案,我想我将在这里分享,以防其他人发现这个线程。背景大小:覆盖的解决方案是最简单的,但我需要一些在IE7中也能工作的东西。这是我用jQuery和CSS设计出来的。

注意:我的图像是"配置文件"图像,需要裁剪为正方形。因此有一些函数名。

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;
 }