CSS 显示调整大小和裁剪的图像

发布于 2024-07-12 13:43:30 字数 1425 浏览 8 评论 0 原文

我想显示来自 URL 的具有特定宽度和高度的图像,即使它具有不同的尺寸比例。 所以我想调整大小(保持比例),然后将图像剪切到我想要的大小。

我可以使用 html img 属性调整大小,并且可以使用 background-image 进行剪切。
我怎样才能两者兼得?

示例:

此图像:

在此处输入图像描述


大小为 800x600 像素,我想显示为 200x100 像素的图像


使用 img 我可以调整图像大小 200x150px

<img 
    style="width: 200px; height: 150px;" 
    src="https://i.sstatic.net/wPh0S.jpg">


这给了我这个:

<img style="width: 200px; height: 150px;" src="https://i.sstatic.net/wPh0S.jpg">


并且使用background-image我可以将图像剪切200x100像素。

<div 
    style="background-image:
           url('https://i.sstatic.net/wPh0S.jpg'); 
    width:200px; 
    height:100px; 
    background-position:center;">&nbsp;</div>

给我:

    <div style="background-image:url('https://i.sstatic.net/wPh0S.jpg'); width:200px; height:100px; background-position:center;">&nbsp;</div>


我怎样才能两者兼得?
调整图像大小,然后将其剪切为我想要的大小?

I want to show an image from an URL with a certain width and height even if it has a different size ratio.
So I want to resize (maintaining the ratio) and then cut the image to the size I want.

I can resize with html img property and I can cut with background-image.

How can I do both?

Example:

This image:

enter image description here

Has the size 800x600 pixels and I want to show like an image of 200x100 pixels

With img I can resize the image 200x150px:

<img 
    style="width: 200px; height: 150px;" 
    src="https://i.sstatic.net/wPh0S.jpg">

That gives me this:

<img style="width: 200px; height: 150px;" src="https://i.sstatic.net/wPh0S.jpg">

And with background-image I can cut the image 200x100 pixels.

<div 
    style="background-image:
           url('https://i.sstatic.net/wPh0S.jpg'); 
    width:200px; 
    height:100px; 
    background-position:center;"> </div>

Gives me:

    <div style="background-image:url('https://i.sstatic.net/wPh0S.jpg'); width:200px; height:100px; background-position:center;"> </div>

How can I do both?

Resize the image and then cut it the size I want?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(21

攀登最高峰 2024-07-19 13:43:30

您可以结合使用这两种方法,例如。

    .crop {
        width: 200px;
        height: 150px;
        overflow: hidden;
    }

    .crop img {
        width: 400px;
        height: 300px;
        margin: -75px 0 0 -100px;
    }
    <div class="crop">
        <img src="https://i.sstatic.net/wPh0S.jpg" alt="Donald Duck">
    </div>

您可以使用负边距

内移动图像。

You could use a combination of both methods eg.

    .crop {
        width: 200px;
        height: 150px;
        overflow: hidden;
    }

    .crop img {
        width: 400px;
        height: 300px;
        margin: -75px 0 0 -100px;
    }
    <div class="crop">
        <img src="https://i.sstatic.net/wPh0S.jpg" alt="Donald Duck">
    </div>

You can use negative margin to move the image around within the <div/>.

四叶草在未来唯美盛开 2024-07-19 13:43:30

使用 CSS3 可以使用 background-image 的大小="noreferrer">background-size,同时实现这两个目标。

大量示例位于 css3.info" rel="noreferrer">css3.info

根据您的示例实现,使用 donald_duck_4.jpg。 在这种情况下,background-size: cover;正是您想要的 - 它适合background-image以覆盖包含

的整个区域; 并剪掉多余的部分(取决于比例)。

.with-bg-size {
  background-image: url('https://i.sstatic.net/wPh0S.jpg');
  width: 200px;
  height: 100px;
  background-position: center;
  /* Make the background image cover the area of the <div>, and clip the excess */
  background-size: cover;
}
<div class="with-bg-size">Donald Duck!</div>

With CSS3 it's possible to change the size of a background-image with background-size, fulfilling both goals at once.

There are a bunch of examples on css3.info.

Implemented based on your example, using donald_duck_4.jpg. In this case, background-size: cover; is just what you want - it fits the background-image to cover the entire area of the containing <div> and clips the excess (depending on the ratio).

.with-bg-size {
  background-image: url('https://i.sstatic.net/wPh0S.jpg');
  width: 200px;
  height: 100px;
  background-position: center;
  /* Make the background image cover the area of the <div>, and clip the excess */
  background-size: cover;
}
<div class="with-bg-size">Donald Duck!</div>

很酷不放纵 2024-07-19 13:43:30

你尝试过使用这个吗?

.centered-and-cropped { object-fit: cover }

我需要调整图像大小、居中(垂直和水平)然后裁剪它。

我很高兴地发现,它可以在单个 css 行中完成。
检查此处的示例: http://codepen.io/chrisnager/pen/azWWgr/? editors=110


以下是该示例中的 CSSHTML 代码:

.centered-and-cropped { object-fit: cover }
<h1>original</h1>
<img height="200" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/3174/bear.jpg" alt="Bear">
    
<h1>object-fit: cover</h1>
<img class="centered-and-cropped" width="200" height="200" 
style="border-radius:50%" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/3174/bear.jpg" alt="Bear">

Did you try to use this?

.centered-and-cropped { object-fit: cover }

I needed to resize image, center (both vertically and horizontally) and than crop it.

I was happy to find, that it could be done in a single css-line.
Check the example here: http://codepen.io/chrisnager/pen/azWWgr/?editors=110


Here is the CSS and HTMLcode from that example:

.centered-and-cropped { object-fit: cover }
<h1>original</h1>
<img height="200" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/3174/bear.jpg" alt="Bear">
    
<h1>object-fit: cover</h1>
<img class="centered-and-cropped" width="200" height="200" 
style="border-radius:50%" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/3174/bear.jpg" alt="Bear">

旧瑾黎汐 2024-07-19 13:43:30
.imgContainer {
  overflow: hidden;
  width: 200px;
  height: 100px;
}
.imgContainer img {
  width: 200px;
  height: 120px;
}
<div class="imgContainer">
  <img src="imageSrc" />
</div>

包含的 div 本质上是通过隐藏溢出来裁剪图像。

.imgContainer {
  overflow: hidden;
  width: 200px;
  height: 100px;
}
.imgContainer img {
  width: 200px;
  height: 120px;
}
<div class="imgContainer">
  <img src="imageSrc" />
</div>

The containing div with essentially crop the image by hiding the overflow.

痴者 2024-07-19 13:43:30
img {
  position: absolute;
  clip: rect(0px, 140px, 140px, 0px);
}
<img src="w3css.gif" width="100" height="140" />
img {
  position: absolute;
  clip: rect(0px, 140px, 140px, 0px);
}
<img src="w3css.gif" width="100" height="140" />
A君 2024-07-19 13:43:30

对之前答案的一个小补充,包括 object-fit: cover

对象位置

您可以使用 object-position 属性更改元素框中被替换元素的内容对象的对齐方式。

.trimmed-cover {
  object-fit: cover;
  width: 100%;
  height: 177px;
  object-position: center 40%;
}
<img class="trimmed-cover" src="https://i.sstatic.net/wPh0S.jpg">

result.gif

A small addition to the previous answers that includes object-fit: cover:

object-position

You can alter the alignment of the replaced element's content object within the element's box using the object-position property.

.trimmed-cover {
  object-fit: cover;
  width: 100%;
  height: 177px;
  object-position: center 40%;
}
<img class="trimmed-cover" src="https://i.sstatic.net/wPh0S.jpg">

result.gif

素衣风尘叹 2024-07-19 13:43:30

谢谢桑乔法特。

我对你的答案有一个改进。 由于裁剪是针对每个图像量身定制的,因此该定义应该位于 HTML 而不是 CSS 中。

<div style="overflow:hidden;">
   <img src="img.jpg" alt="" style="margin:-30% 0px -10% 0px;" />
</div>

Thanks sanchothefat.

I have an improvement to your answer. As crop is very tailored for every image, this definitions should be at the HTML instead of CSS.

<div style="overflow:hidden;">
   <img src="img.jpg" alt="" style="margin:-30% 0px -10% 0px;" />
</div>
我最亲爱的 2024-07-19 13:43:30

如果您使用 标签,

object-fit 可能会对您有所帮助

下面的代码将为您裁剪图像。 您可以使用 object-fit

img {
  object-fit: cover;
  width: 300px;
  height: 337px;
}

object-fit may help you, if you're playing with <img> tag

The below code will crop your image for you. You can play around with object-fit

img {
  object-fit: cover;
  width: 300px;
  height: 337px;
}
转瞬即逝 2024-07-19 13:43:30
img {
    position: absolute;
    clip: rect(0px,60px,200px,0px);
} 
img {
    position: absolute;
    clip: rect(0px,60px,200px,0px);
} 
情未る 2024-07-19 13:43:30

尝试使用 clip-path 属性:

clip-path 属性允许您将元素剪辑为基本形状或
SVG 源。

注意:clip-path 属性将替换已弃用的剪辑
属性。

img {
  width: 150px;
  clip-path: inset(30px 35px);
}
<img src="https://i.sstatic.net/wPh0S.jpg">

更多示例此处

Try using the clip-path property:

The clip-path property lets you clip an element to a basic shape or to
an SVG source.

Note: The clip-path property will replace the deprecated clip
property.

img {
  width: 150px;
  clip-path: inset(30px 35px);
}
<img src="https://i.sstatic.net/wPh0S.jpg">

More examples here.

花开半夏魅人心 2024-07-19 13:43:30

实例:
https://jsfiddle.net/de4Lt57z/

HTML:

<div class="crop">
  <img src="example.jpg" alt="..." />
</div>

CSS:

    .crop img{
      width:400px;
      height:300px;
      position: absolute;
      clip: rect(0px,200px, 150px, 0px);
      }

说明:
这里图像的大小是根据图像的宽度和高度值调整的。 裁剪是通过clip属性完成的。

有关剪辑属性的详细信息,请参见:
http://tympanus.net/codrops/2013/ 01/16/理解-css-clip-property/

Live Example:
https://jsfiddle.net/de4Lt57z/

HTML:

<div class="crop">
  <img src="example.jpg" alt="..." />
</div>

CSS:

    .crop img{
      width:400px;
      height:300px;
      position: absolute;
      clip: rect(0px,200px, 150px, 0px);
      }

Explanation:
Here image is resized by width and height value of the image. And crop is done by clip property.

For details about clip property follow:
http://tympanus.net/codrops/2013/01/16/understanding-the-css-clip-property/

ぃ双果 2024-07-19 13:43:30

在裁剪类中,放置您想要显示的图像尺寸:

.crop {
    width: 282px;
    height: 282px;
    overflow: hidden;
}
.crop span.img {
    background-position: center;
    background-size: cover;
    height: 282px;
    display: block;
}

html 将如下所示:

<div class="crop">
    <span class="img" style="background-image:url('http://url.to.image/image.jpg');"></span>
</div>

In the crop class, place the image size that you want to appear:

.crop {
    width: 282px;
    height: 282px;
    overflow: hidden;
}
.crop span.img {
    background-position: center;
    background-size: cover;
    height: 282px;
    display: block;
}

The html will look like:

<div class="crop">
    <span class="img" style="background-image:url('http://url.to.image/image.jpg');"></span>
</div>
把回忆走一遍 2024-07-19 13:43:30
<p class="crop"><a href="http://templatica.com" title="Css Templates">
    <img src="img.jpg" alt="css template" /></a></p> 

.crop {
    float: left;
    margin: .5em 10px .5em 0;
    overflow: hidden; /* this is important */
    position: relative; /* this is important too */
    border: 1px solid #ccc;
    width: 150px;
    height: 90px;
}
.crop img {
    position: absolute;
    top: -20px;
    left: -55px;
}
<p class="crop"><a href="http://templatica.com" title="Css Templates">
    <img src="img.jpg" alt="css template" /></a></p> 

.crop {
    float: left;
    margin: .5em 10px .5em 0;
    overflow: hidden; /* this is important */
    position: relative; /* this is important too */
    border: 1px solid #ccc;
    width: 150px;
    height: 90px;
}
.crop img {
    position: absolute;
    top: -20px;
    left: -55px;
}
灯下孤影 2024-07-19 13:43:30

服务(例如 Filestack)可以为您完成此操作。

它们获取您的图像网址并允许您使用网址参数调整其大小。 这很容易。

调整大小到 200x100 但保持宽高比后,您的图像将如下所示

整个网址看起来像这样

https://process.filestackapi.com/AhTgLagciQByzXpFGRI0Az/resize=width:200/crop=d:[0,25,200,100]/https://i.sstatic.net/wPh0S.jpg

,但重要的部分只是

resize=width:200/crop=d:[0,25,200,100]

在此处输入图像描述

There are services like Filestack that will do this for you.

They take your image url and allow you to resize it using url parameters. It is pretty easy.

Your image would look like this after resizing to 200x100 but keeping the aspect ratio

The whole url looks like this

https://process.filestackapi.com/AhTgLagciQByzXpFGRI0Az/resize=width:200/crop=d:[0,25,200,100]/https://i.sstatic.net/wPh0S.jpg

but the important part is just

resize=width:200/crop=d:[0,25,200,100]

enter image description here

じее 2024-07-19 13:43:30

您可以将 img 标签放在 div 标签中并同时执行这两项操作,但我建议不要在浏览器中缩放图像。 大多数时候它的表现很糟糕,因为浏览器的缩放算法非常简单。 最好先在 Photoshop 或 ImageMagick 中进行缩放,然后将其漂亮漂亮地提供给客户。

You can put the img tag in a div tag and do both, but I would recommend against scaling images in the browser. It does a lousy job most of the time because browsers have very simplistic scaling algorithms. Better to do your scaling in Photoshop or ImageMagick first, then serve it up to the client nice and pretty.

飞烟轻若梦 2024-07-19 13:43:30

我所做的是创建一个服务器端脚本,该脚本将在服务器端调整图片大小并裁剪图片,以便通过互联网发送更少的数据。

这是相当微不足道的,但如果有人感兴趣,我可以挖掘并发布代码(asp.net)

What I've done is to create a server side script that will resize and crop a picture on the server end so it'll send less data across the interweb.

It's fairly trivial, but if anyone is interested, I can dig up and post the code (asp.net)

空‖城人不在 2024-07-19 13:43:30
<div class="crop">
    <img src="image.jpg"/>
</div>
.crop {
  width: 200px;
  height: 150px;
  overflow: hidden;
}
.crop img {
  width: 100%;
  /*Here you can use margins for accurate positioning of cropped image*/
}
<div class="crop">
    <img src="image.jpg"/>
</div>
.crop {
  width: 200px;
  height: 150px;
  overflow: hidden;
}
.crop img {
  width: 100%;
  /*Here you can use margins for accurate positioning of cropped image*/
}
成熟稳重的好男人 2024-07-19 13:43:30

如果您使用 Bootstrap,请尝试使用 { background-size: cover;
}
对于

可以给 div 一个类,比如

所以就变成了
div.示例{
背景大小:封面}

If you are using Bootstrap, try using { background-size: cover;
}
for the <div> maybe give the div a class say <div class="example" style=url('../your_image.jpeg');> so it becomes
div.example{
background-size: cover}

作业与我同在 2024-07-19 13:43:30

我最近需要这样做。 我想制作一个 NOAA 图表的缩略图链接。 由于他们的图表可能随时更改,因此我希望我的缩略图也随之更改。 但他们的图表存在一个问题:它的顶部有一个巨大的白色边框,因此如果您只是缩放它以制作缩略图,最终会在文档中出现无关的空白。

这是我解决问题的方法:

http://sealevel.info/example_css_scale_and_crop.html

首先我需要做一点算术。 NOAA 的原始图像为 960 × 720 像素,但顶部 70 个像素是多余的白色边框区域。 我需要一个 348 × 172 的缩略图,顶部没有多余的边框区域。 这意味着原始图像的所需部分高为 720 - 70 = 650 像素。 我需要将其缩小到 172 像素,即 172 / 650 = 26.5%。 这意味着需要从缩放图像的顶部删除 70 = 19 行像素中的 26.5%。

所以...

  1. 设置高度 = 172 + 19 = 191 像素:

    height=191

  2. 将下边距设置为 -19 像素(将图像缩短至 172 像素高):

    ma​​rgin-bottom:-19px

  3. 将顶部位置设置为 -19 像素(将图像向上移动,以便顶部 19 像素行溢出并隐藏,而不是底部的行):

    top:-19px

生成的 HTML 如下所示:

<a href="…" style="display:inline-block;overflow:hidden">
<img width=348 height=191 alt=""
style="border:0;position:relative;margin-bottom:-19px;top:-19px"
src="…"></a>

如您所见,我选择对包含 的样式进行样式设置。 标签,但您可以设置

的样式。

这种方法的一个缺陷是,如果显示边框,则顶部边框将会丢失。 因为无论如何我都使用 border=0,所以这对我来说不是问题。

I needed to do this recently. I wanted to make a thumbnail-link to a NOAA graph. Since their graph could change at any time, I wanted my thumbnail to change with it. But there's a problem with their graph: it has a huge white border at the top, so if you just scale it to make the thumbnail you end up with extraneous whitespace in the document.

Here's how I solved it:

http://sealevel.info/example_css_scale_and_crop.html

First I needed to do a little bit of arithmetic. The original image from NOAA is 960 × 720 pixels, but the top seventy pixels are a superfluous white border area. I needed a 348 × 172 thumbnail, without the extra border area at the top. That means the desired part of the original image is 720 - 70 = 650 pixels high. I needed to scale that down to 172 pixels, i.e., 172 / 650 = 26.5%. That meant 26.5% of 70 = 19 rows of pixels needed to be deleted from the top of the scaled image.

So…

  1. Set the height = 172 + 19 = 191 pixels:

    height=191

  2. Set the bottom margin to -19 pixels (shortening the image to 172 pixels high):

    margin-bottom:-19px

  3. Set the top position to -19 pixels (shifting the image up, so that the top 19 pixel rows overflow & are hidden instead of the bottom ones):

    top:-19px

The resulting HTML looks like this:

<a href="…" style="display:inline-block;overflow:hidden">
<img width=348 height=191 alt=""
style="border:0;position:relative;margin-bottom:-19px;top:-19px"
src="…"></a>

As you can see, I chose to style the containing <a> tag, but you could style a <div>, instead.

One artifact of this approach is that if you show the borders, the top border will be missing. Since I use border=0 anyhow, that wasn't an issue for me.

酒几许 2024-07-19 13:43:30

您可以使用 Kodem 的图像调整大小服务。 您只需调用 http 即可调整任何图像的大小。 可以在浏览器中随意使用,也可以在您的生产应用程序中使用。

  • 将图像上传到您喜欢的位置(S3、imgur 等)
  • 将其插入您的专用 API url(来自我们的仪表板)

You can use Kodem's Image Resize Service. You can resize any image with just a http call. Can be used casually in the browser or used in your production app.

  • Upload the image somewhere you prefer (S3, imgur etc.)
  • Plug it into your dedicated API url (from our dashboard)
十年九夏 2024-07-19 13:43:30

您还可以使用名为 Croppie 的工具来裁剪图像......

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<link href="https://foliotek.github.io/Croppie/croppie.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"> </script>
<script src="https://foliotek.github.io/Croppie/croppie.js"> </script>
<script src="https://foliotek.github.io/Croppie/bower_components/exif-js/exif.js"> </script>

<style>
    #page {
        background: #ffffff;
        padding: 20px;
        margin: 20px;
    }

    #demo-basic {
        width: 600px;
        height: 600px;
    }
</style>
</head>
<body>
<h1>Crop Image Demo</h1>
<input id="upload" type="file" />
<br />
<div id="page">
<div id="demo-basic"></div>
</div>

<input id="upload-result" type="button" value="Crop Image"/>
<br />
<img id="cropped-result" src=""/>

<script>
    var $uploadCrop;       

    $("#upload").on("change", function () { readFile(this); show(); });

    $("#upload-result").on("click", function (ev) {
        $uploadCrop.croppie("result", {
            type: "canvas",
            size: "viewport"
        }).then(function (resp) {
            $("#cropped-result").attr("src", resp);
        });
    });

    function show() {
        $uploadCrop = $("#demo-basic").croppie({
            viewport: { width: 100, height: 100 },
            boundary: { width: 300, height: 300 },
            enableResize: true,
            enableOrientation: true,
            mouseWheelZoom: 'ctrl',
            enableExif: true
        });
    }

    function readFile(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();
        
            reader.onload = function (e) {
                $("#demo-basic").addClass("ready");
                $uploadCrop.croppie("bind", {
                    url: e.target.result
                }).then(function () {
                    console.log("jQuery bind complete");
                });
            
            }
        
            reader.readAsDataURL(input.files[0]);
        }
        else {
            alert("Sorry - you're browser doesn't support the FileReader API");
        }
    }
</script>
</body>
</html>

You can also use a tool called Croppie that can crop images...

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<link href="https://foliotek.github.io/Croppie/croppie.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"> </script>
<script src="https://foliotek.github.io/Croppie/croppie.js"> </script>
<script src="https://foliotek.github.io/Croppie/bower_components/exif-js/exif.js"> </script>

<style>
    #page {
        background: #ffffff;
        padding: 20px;
        margin: 20px;
    }

    #demo-basic {
        width: 600px;
        height: 600px;
    }
</style>
</head>
<body>
<h1>Crop Image Demo</h1>
<input id="upload" type="file" />
<br />
<div id="page">
<div id="demo-basic"></div>
</div>

<input id="upload-result" type="button" value="Crop Image"/>
<br />
<img id="cropped-result" src=""/>

<script>
    var $uploadCrop;       

    $("#upload").on("change", function () { readFile(this); show(); });

    $("#upload-result").on("click", function (ev) {
        $uploadCrop.croppie("result", {
            type: "canvas",
            size: "viewport"
        }).then(function (resp) {
            $("#cropped-result").attr("src", resp);
        });
    });

    function show() {
        $uploadCrop = $("#demo-basic").croppie({
            viewport: { width: 100, height: 100 },
            boundary: { width: 300, height: 300 },
            enableResize: true,
            enableOrientation: true,
            mouseWheelZoom: 'ctrl',
            enableExif: true
        });
    }

    function readFile(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();
        
            reader.onload = function (e) {
                $("#demo-basic").addClass("ready");
                $uploadCrop.croppie("bind", {
                    url: e.target.result
                }).then(function () {
                    console.log("jQuery bind complete");
                });
            
            }
        
            reader.readAsDataURL(input.files[0]);
        }
        else {
            alert("Sorry - you're browser doesn't support the FileReader API");
        }
    }
</script>
</body>
</html>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文