javascript 设置图像最大尺寸

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6844433/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 22:04:00  来源:igfitidea点击:

Set image max size

javascripthtmlimageimage-size

提问by Harry Joy

I need to set maximum height and width of a image in <img>tag. For example say max size is 400x400 px so if the image size is smaller than this then it will show the image as it is and if size is bigger then this then it should be compressed to this size. How can I do this in html or javascript?

我需要在<img>标签中设置图像的最大高度和宽度。例如,假设最大尺寸为 400x400 像素,因此如果图像尺寸小于此尺寸,则它将按原样显示图像,如果尺寸更大,则应将其压缩到此尺寸。我怎样才能在 html 或 javascript 中做到这一点?

回答by tskuzzy

Set the max-widthand max-heightin CSS

在 CSS 中设置max-widthmax-height

max-width: 400px;
max-height: 400px;

回答by joncodo

try using a div tag of that size and putting image inside:

尝试使用该大小的 div 标签并将图像放入其中:

<div style="width:400px; height400px;>

  <img style="text-align:center; vertical-align:middle; max-width:400px;  max-height:400px;" />

</div>

or something like that. The div is the full size and the image can only expand to its borders.

或类似的东西。div 是完整尺寸,图像只能扩展到其边框。

回答by Internet Engineer

The way I did it:

我是这样做的:

  • When the image is being uploaded I use a server side library to resize if the image is bigger (only). You always resize down, never up.
  • Then on the client side I do not set the image size.
  • 上传图像时,如果图像更大(仅),我会使用服务器端库来调整大小。你总是缩小尺寸,从不放大。
  • 然后在客户端我没有设置图像大小。

The image will be 400x400 only for those images that were exactly that size or bigger.

仅对于那些尺寸正好或更大的图像,图像才会为 400x400。

回答by Stan

img
{
    max-width: 400px;
    max-height: 400px;
}

Like so: http://jsfiddle.net/fMuVw/

像这样:http: //jsfiddle.net/fMuVw/

回答by Micha? Stochmal

You can also use object-fit: scale-downto make image fit a container size if it's too big and leave image size as is if it's smaller than the container.

如果object-fit: scale-down图像太大,您还可以使用使图像适合容器大小,并保持图像大小不变,如果它小于容器。

CSS:

CSS:

.img-scale-down {
    width: 100%;
    height: 100%;
    object-fit: scale-down;
    overflow: hidden;
}

HTML:

HTML:

<div style="width: 400px;">
   <img src="myimage.jpg" class="img-scale-down"/>
</div>