Home  >  Article  >  Web Front-end  >  How to Resize Images Proportionally with jQuery?

How to Resize Images Proportionally with jQuery?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-04 07:34:30755browse

How to Resize Images Proportionally with jQuery?

Preserving Image Proportions with jQuery

Resizing images proportionally is crucial to maintain their visual integrity. jQuery offers a straightforward solution to scale images while preserving their aspect ratio.

How to Calculate Proportional Dimensions

The following function determines the appropriate width and height for the resized image:

<code class="js">function calculateAspectRatioFit(srcWidth, srcHeight, maxWidth, maxHeight) {

    var ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight);

    return { width: srcWidth*ratio, height: srcHeight*ratio };
 }</code>

This function accepts the original image dimensions (srcWidth, srcHeight) and the maximum available width and height (maxWidth, maxHeight) as parameters. It calculates the minimum ratio between the original and maximum dimensions to preserve the aspect ratio. The new width and height are then determined by multiplying the original values by this ratio.

Applying the Logic with jQuery

Once you have calculated the new dimensions, you can use jQuery to resize the image:

<code class="js">var newDimensions = calculateAspectRatioFit(srcWidth, srcHeight, maxWidth, maxHeight);

$("img").width(newDimensions.width);
$("img").height(newDimensions.height);</code>

This code dynamically sets the width and height attributes of the selected image element to the calculated values.

The above is the detailed content of How to Resize Images Proportionally with jQuery?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn