---
title: "How to auto-resize an image while maintaining aspect ratio?"  
description: "How to auto-resize an image while maintaining aspect ratio?"  
author: "Utpal Vishwas"  
published: 2023-07-31  
updated: 2023-08-01  
canonical: https://www.mindstick.com/forum/159383/how-to-auto-resize-an-image-while-maintaining-aspect-ratio  
category: "javascript"  
tags: ["javascript", "image view", "image optimization"]  
reading_time: 2 minutes  

---

# How to auto-resize an image while maintaining aspect ratio?

How to [auto](https://www.mindstick.com/forum/33810/remote-view-in-android-auto-cancel-custom-notification)-resize an [image](https://www.mindstick.com/articles/23551/an-investigate-distinctive-seafood-restaurant-for-your-image-stamp-character) while maintaining the [aspect](https://yourviews.mindstick.com/view/81162/finding-deglobalization-aspect-in-corona-pandemic) ratio?

## Replies

### Reply by Aryan Kumar

Sure, here are a few ways to auto resize an image while maintaining aspect ratio:

## Using CSS

You can use the `width` and `height` properties of the `img` element to auto resize an image while maintaining aspect ratio. For example, the following CSS will resize an image to be 100px wide and will maintain the aspect ratio of the image:

CSS

```plaintext
img {
  width: 100px;
  height: auto;
}
```

## Using JavaScript

You can also use JavaScript to auto resize an image while maintaining aspect ratio. The following JavaScript code will resize an image to be 100px wide and will maintain the aspect ratio of the image:

JavaScript

```plaintext
function resizeImage(image, width) {
  var height = image.height * (width / image.width);
  image.width = width;
  image.height = height;
}

// Resize the image
resizeImage(document.getElementById("myImage"), 100);
```

## Using the Sharp library

You can also use the Sharp library to auto resize an image while maintaining aspect ratio. The Sharp library is a popular image processing library for Node.js. The following code will resize an image to be 100px wide and will maintain the aspect ratio of the image:

JavaScript

```plaintext
const sharp = require("sharp");

// Resize the image
const resizedImage = await sharp(imagePath)
  .resize(100)
  .toBuffer();

// Save the resized image
const resizedImagePath = "resized-image.jpg";
await resizedImage.save(resizedImagePath);
```


---

Original Source: https://www.mindstick.com/forum/159383/how-to-auto-resize-an-image-while-maintaining-aspect-ratio

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
