0

Is there anyway to resize an image without distorting it?

I have a 70px thumbnail image and I need to resize it to 200px X 165px while maintaining the aspect ratio. At the moment it stretches it when I set the width: 200px and height: 165px.

Here is the code:

CSS

.listing-img-div {
    width: 200px;
    height: 165px;
}

.listing-img {
    border: 1px solid black;
    margin-top: 5px;
    border: 1px solid #ddd;
    width: 100%;
    height: 100%;
}

HTML/PHP

echo '<div class="listing-img-div">';
  echo '<img class="listing-img" src="'.$img.'" alt="'.$title.'">';                                                     echo '</div>';
dgolman
  • 196
  • 1
  • 13
  • If your container is `200px wide`, you can use `img { max-width:100%; height:auto; }` This will stretch the image to the width of the containing div while keeping the aspect ratio - if you're increasing the size you will notice some blurriness obviously. It would help if you could post your HTML and CSS though. – Nick R Jul 18 '13 at 13:04

2 Answers2

6

If it is not an SVG or any type of a Vector Type image, stretching it will result in the loss of quality, because such types as JPG, BMP, PNG are of lossy type.

Simple resize, however, can be achieved like so by maintaining the aspect ratio:

img {
   height: 165px;
   width: auto;
   max-width: 200px;
   max-height: 165px;
}

or

img {
   height: auto;
   width: 200px;
   max-width: 200px;
   max-height: 165px;
}

Explanation:

You give either fixed width or fixed height by default. Whichever is more important to you. The force the remaining parameter to scale automatically, hence, auto. After that you override with additional attributes for the images to scale so that, in case they need to resize, they will get smaller + max-width/max-height is not supported in IE6 or lower, which is why you still might want a fallback to a fixed size.

Mohammad Areeb Siddiqui
  • 9,795
  • 14
  • 71
  • 113
achudars
  • 1,486
  • 15
  • 25
  • please explain him aswell what's happening there! :) Then == +1 :) – Mohammad Areeb Siddiqui Jul 18 '13 at 13:34
  • you give either fixed width or fixed height by default. Whichever is more important to you. Then force the remaining parameter to scale automatically, hence, auto. After that you override with additional attributes for the images to scale so that, in case they need to resize, they will get smaller + max-width/max-height is not supported in IE6 or lower, which is why you still might want a fallback to a fixed size. – achudars Jul 18 '13 at 13:49
  • you had to give it to him, not to me! Edited! :) – Mohammad Areeb Siddiqui Jul 18 '13 at 13:50
1

You can also just set width to auto and height to 100%.

img {
   width: auto;
   max-height: 100%;
}

And as said by others until an image is not a vector or is not an SVG it will always result in loss of quality.

Stano
  • 8,749
  • 6
  • 30
  • 44
Mohammad Areeb Siddiqui
  • 9,795
  • 14
  • 71
  • 113