如何自动裁剪和居中图像 [英] How to automatically crop and center an image

查看:659
本文介绍了如何自动裁剪和居中图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定任意图像,我要从图像中心裁剪一个正方形,并在给定的正方形内显示。

Given any arbitrary image, I want to crop a square from the center of the image and display it within a given square.

这个问题与此类似: CSS显示调整大小和裁剪的图片,但我不知道图像的大小,所以我不能使用设置边距。

This question is similar to this: CSS Display an Image Resized and Cropped, but I don't know the size of the image so I can't use set margins.

推荐答案

一种解决方案是使用以裁剪尺寸为尺寸的元素为中心的背景图片。

One solution is to use a background image centered within an element sized to the cropped dimensions.

.center-cropped {
  width: 100px;
  height: 100px;
  background-position: center center;
  background-repeat: no-repeat;
}

<div class="center-cropped" 
     style="background-image: url('http://placehold.it/200x200');">
</div>

此版本保留了 img 标记,因此我们不会失去拖动或右键单击的能力保存图像。归功于 Parker Bennett 的不透明度技巧。

This version retains the img tag so that we do not lose the ability to drag or right-click to save the image. Credit to Parker Bennett for the opacity trick.

.center-cropped {
  width: 100px;
  height: 100px;
  background-position: center center;
  background-repeat: no-repeat;
  overflow: hidden;
}

/* Set the image to fill its parent and make transparent */
.center-cropped img {
  min-height: 100%;
  min-width: 100%;
  /* IE 8 */
  -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
  /* IE 5-7 */
  filter: alpha(opacity=0);
  /* modern browsers */
  opacity: 0;
}

<div class="center-cropped" 
     style="background-image: url('http://placehold.it/200x200');">
  <img src="http://placehold.it/200x200" />
</div>

查看支持的浏览器

CSS3图片规格定义 object-fit object-position 属性,它们一起允许更好地控制 img 元素的图像内容。有了这些,就可以达到预期的效果:

The CSS3 Images specification defines the object-fit and object-position properties which together allow for greater control over the scale and position of the image content of an img element. With these, it will be possible to achieve the desired effect:

.center-cropped {
  object-fit: none; /* Do not scale the image */
  object-position: center; /* Center the image within the element */
  height: 100px;
  width: 100px;
}

<img class="center-cropped" src="http://placehold.it/200x200" />

这篇关于如何自动裁剪和居中图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆