[英]Set image max size
I need to set maximum height and width of a image in <img>
tag.我需要在<img>
标签中设置图像的最大高度和宽度。 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.例如,假设最大尺寸为 400x400 像素,因此如果图像尺寸小于此尺寸,则它将按原样显示图像,如果尺寸更大,则应将其压缩到此尺寸。 How can I do this in html or javascript?我怎样才能在 html 或 javascript 中做到这一点?
Set the max-width
and max-height
in CSS 在CSS中设置max-width
和max-height
max-width: 400px;
max-height: 400px;
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是完整大小,图像只能扩展到其边框。
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. 您还可以使用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>
The way I did it: 我这样做的方式:
The image will be 400x400 only for those images that were exactly that size or bigger. 仅对于那些尺寸或更大尺寸的图像,图像将为400x400。
img
{
max-width: 400px;
max-height: 400px;
}
Like so: http://jsfiddle.net/fMuVw/ 像这样: http : //jsfiddle.net/fMuVw/
In JavaScript you can use:在 JavaScript 中,您可以使用:
/* getting the image */
var img = document.createElement('img');
img.src = "img.png";
/* setting max width and height */
document.getElementById("id").appendChild(img).style.maxWidth = "400px";
document.getElementById("id").appendChild(img).style.maxHeight = "400px";
/* inserting image */
document.getElementById("id").appendChild(img);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.