Home > Article > Web Front-end > How to Resize Images Proportionally While Maintaining Aspect Ratio?
How to Resize Images Proportionally
Resizing images proportionally is a common task that can be used to fit images into specific dimensions while maintaining their aspect ratio. This is especially useful when working with images of different sizes that need to be displayed consistently.
To resize an image proportionally using jQuery, you can use the following code:
<code class="javascript">$('img').css({ 'max-width': '100%', 'max-height': '100%', 'width': 'auto', 'height': 'auto' });</code>
This code sets the maximum width and height of the image to 100%, which allows the image to scale proportionally to fit within these dimensions. The 'width' and 'height' properties are set to 'auto' to maintain the original aspect ratio.
Another method for calculating the appropriate dimensions for an image while preserving its aspect ratio is to use the calculateAspectRatioFit() function:
<code class="javascript">function calculateAspectRatioFit(srcWidth, srcHeight, maxWidth, maxHeight) { var ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight); return { width: srcWidth*ratio, height: srcHeight*ratio }; }</code>
This function takes the original width and height of the image, along with the maximum available width and height, and calculates the new width and height that maintain the aspect ratio within the specified limits.
The above is the detailed content of How to Resize Images Proportionally While Maintaining Aspect Ratio?. For more information, please follow other related articles on the PHP Chinese website!