Last active
March 17, 2017 12:19
-
-
Save kaugesaar/be62c660205be73f6b5fd4d392daf689 to your computer and use it in GitHub Desktop.
Resize an image based on the area of another image while maintaining the same ratio as before.
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
/** | |
* Resize an image based on the area of another image | |
* while maintaining the same ratio as before. | |
* | |
* @param width {Number} the width of the image not to be resized | |
* @param height {Number} the height of the image not to be resized | |
* @param rWidth {Number} the width of the image to be resized | |
* @param rHeight {Number} the height of the image to be resized | |
* @param resize {Float} decimal percentage of how much to resize | |
*/ | |
function calc(width, height, rWidth, rHeight, resize) { | |
// Calculate the comparison image area | |
var area = width * height; | |
// The total area of the resized imaged | |
var targetArea = area * resize; | |
// Get the ratio of the picture | |
var ratio = (rWidth > rHeight) ? rWidth / rHeight : rHeight / rWidth; | |
// If horizontal make the width larger than the height | |
if(rWidth > rHeight) { | |
return { | |
width: Math.sqrt(targetArea) * Math.sqrt(ratio), | |
height: Math.sqrt(targetArea) / Math.sqrt(ratio), | |
} | |
} | |
// If vertical or square make the height larger than the width | |
return { | |
width: Math.sqrt(targetArea) / Math.sqrt(ratio), | |
height: Math.sqrt(targetArea) * Math.sqrt(ratio), | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment