Set image max size
Asked Answered
B

6

9

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?

Banjo answered 27/7, 2011 at 12:39 Comment(0)
L
11

Set the max-width and max-height in CSS

max-width: 400px;
max-height: 400px;
Linnet answered 27/7, 2011 at 12:47 Comment(0)
S
6

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>
Slating answered 11/12, 2018 at 11:12 Comment(0)
H
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.

Hudson answered 27/7, 2011 at 12:44 Comment(0)
C
1

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.

Callas answered 27/7, 2011 at 12:46 Comment(0)
U
1

In JavaScript you can use:

/* 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);
Uncommercial answered 17/10, 2021 at 19:34 Comment(1)
While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. You can find more information on how to write good answers in the help center: stackoverflow.com/help/how-to-answer . Good luck 🙂Goldofpleasure
S
0
img
{
    max-width: 400px;
    max-height: 400px;
}

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

Sardinia answered 27/7, 2011 at 12:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.