Coder Perfect

How to use the HTML IMG tag to keep the aspect ratio?

Problem

In our application, I’m displaying a photo using the HTML img tag. Both the height and width attributes have been set to 64. Any image resolution (e.g. 256×256, 1024×768, 500×400, 205×246, etc.) must be displayed as 64×64. However, by setting the height and width attributes of an img element to 64, the aspect ratio is not maintained, and the image appears deformed.

For your convenience, here is my exact code:

<img src="Runtime Path to photo" border="1" height="64" width="64">

Asked by sunil kumar

Solution #1

Set neither the height nor the width. The right aspect ratio will be preserved if you use one or the other.

Answered by Turnip

Solution #2

here is the sample one

Answered by AKHIL P

Solution #3

Set the photos’ width and height to auto, but set the max-width and max-height limits:

img {
    max-width:64px;
    max-height:64px;
    width:auto;
    height:auto;
}

Fiddle

You can use inline-block wrappers and positioning to display images of any size in the 64x64px “frames,” as demonstrated in this tinker.

Answered by Ilya Streltsyn

Solution #4

<img src="Runtime Path to photo"
     style="border: 1px solid #000; max-width:64px; max-height:64px;">

Answered by Lucio Fonseca

Solution #5

Use object-fit: include in the css of the img html element.

ex:

img {
    ...
    object-fit: contain
    ...
}

Answered by Ankit Kumar Verma

Post is based on https://stackoverflow.com/questions/12912048/how-to-maintain-aspect-ratio-using-html-img-tag