Set image max size

和自甴很熟 提交于 2019-12-19 17:34:29

问题


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?


回答1:


Set the max-width and max-height in CSS

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



回答2:


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

<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.




回答3:


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.




回答4:


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

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




回答5:


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

CSS:

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

HTML:

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


来源:https://stackoverflow.com/questions/6844433/set-image-max-size

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!