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: 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="http://i.stack.imgur.com/wPh0S.jpg"> That gives me this: <img style="width: 200px; height: 150px;" src="https://i.stack.imgur.com/wPh0S.jpg"> And with background-image I can cut the image 200x100 pixels. <div style="background-image: url('https://i.stack.imgur.com/wPh0S.jpg'); width:200px; height:100px; background-position:center;">&nbsp;</div> Gives me: <div style="background-image:url('https://i.stack.imgur.com/wPh0S.jpg'); width:200px; height:100px; background-position:center;">&nbsp;</div> How can I do both? Resize the image and then cut it the size I want?


当前回答

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

上传图片到你喜欢的地方(S3, imgur等) 将其插入到您的专用API url(从我们的仪表板)

其他回答

您可以将img标记放在div标记中,但我建议不要在浏览器中缩放图像。它在大多数时候都做得很糟糕,因为浏览器的缩放算法非常简单。最好先在Photoshop或ImageMagick中进行缩放,然后将其漂亮地提供给客户端。

你可以把两种方法结合起来使用。

.crop { 宽度:200 px; 身高:150 px; 溢出:隐藏; } .crop img { 宽度:400 px; 身高:300 px; Margin: -75px 00 -100px; } < div class = "作物”> <img src="https://i.stack.imgur.com/wPh0S.jpg" alt="唐老鸭"> < / div >

您可以使用负边距在<div/>内移动图像。

<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*/
}
.imgContainer {
  overflow: hidden;
  width: 200px;
  height: 100px;
}
.imgContainer img {
  width: 200px;
  height: 120px;
}
<div class="imgContainer">
  <img src="imageSrc" />
</div>

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

如果你正在使用Bootstrap,尝试使用{background-size: cover; }对于<div>可能给div一个类说<div class="example" style=url('../your_image.jpeg');>所以它变成 div.example { background-size:封面}