Last active
August 14, 2023 22:37
-
-
Save BilalQadri/dc71a6f7a4a1c8c0fc0bc7f2322d0202 to your computer and use it in GitHub Desktop.
Resize Image (keeping aspect ratio) of HTML with Javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// jquery required | |
// maxWidth and maxHeight can be parameters for more flexibility | |
function (img_ref) { | |
var img = $(img_ref); | |
img.on('load', function () { | |
img.css("width", "auto"); | |
img.css("height", "auto"); | |
var maxWidth = 180; // Max width for the image | |
var maxHeight = 180; // Max height for the image | |
var ratio = 0; // Used for aspect ratio | |
var width = img.width(); // Current image width | |
var height = img.height(); // Current image height | |
if (width > maxWidth && width > height) { | |
ratio = width / height; | |
img.css("height", maxWidth/ratio); | |
img.css("width", maxWidth); // Set new width | |
}else if (height > maxHeight && height > width){ | |
ratio = height / width; | |
img.css("width", maxHeight/ratio); | |
img.css("height", maxHeight); | |
}else { | |
img.css("width", maxWidth); | |
img.css("height", maxHeight); | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment