CSS比例和方形中心裁剪图像

时间:2013-05-01 00:12:34

标签: javascript jquery html css image

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

目前它只是拉伸图像以适应缩略图,所以说我的原始图像尺寸 400x800 ,然后图像看起来非常挤压。我想裁剪此图像,使其查看最短的宽度/高度,然后将其裁剪为正方形,因此在上面的示例中,它将被裁剪为 400x400

有没有办法通过CSS轻松完成此操作,还是必须使用某种JS来执行此操作?

3 个答案:

答案 0 :(得分:49)

如果您使用背景图像,则可以在CSS中轻松完成此操作。

.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

答案 1 :(得分:9)

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

您可以使用纯CSS执行此操作。将每个图像的容器元素设置为具有固定的高度和宽度overflow: hidden。然后将图片设置为min-width: 100%min-height: 100%。任何额外的高度或宽度都会溢出容器并被隐藏。

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

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

答案 2 :(得分:1)

我提出了自己的解决方案,并认为我会在这里分享它以防其他人找到这个帖子。背景大小:封面解决方案是最简单的,但我需要一些可以在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;
 }
相关问题