Skip to content

Instantly share code, notes, and snippets.

@leonidkuznetsov18
Created December 18, 2022 12:17
Show Gist options
  • Save leonidkuznetsov18/d26335b28577763db21b76e42b4a1aa4 to your computer and use it in GitHub Desktop.
Save leonidkuznetsov18/d26335b28577763db21b76e42b4a1aa4 to your computer and use it in GitHub Desktop.
Crop Image
function cropImage(cropMode, sourceWidth, sourceHeight, targetD) {
let result = {};
if (cropMode === 'Fill') {
result.width = targetD;
result.height = targetD;
if (sourceWidth > sourceHeight) {
result.type = 'landscape';
} else if (sourceWidth < sourceHeight) {
result.type = 'portrait';
} else {
result.type = 'square';
}
} else if (cropMode === 'Fit') {
if (sourceWidth > sourceHeight) {
result.width = targetD;
result.height = Math.round((sourceHeight / sourceWidth) * targetD);
result.type = 'landscape';
} else if (sourceWidth < sourceHeight) {
result.width = Math.round((sourceWidth / sourceHeight) * targetD);
result.height = targetD;
result.type = 'portrait';
} else {
result.width = targetD;
result.height = targetD;
result.type = 'square';
}
} else if (cropMode === 'Letterbox') {
if (sourceWidth > sourceHeight) {
result.width = Math.round((sourceWidth / sourceHeight) * targetD);
result.height = targetD;
result.type = 'landscape';
} else if (sourceWidth < sourceHeight) {
result.width = targetD;
result.height = Math.round((sourceHeight / sourceWidth) * targetD);
result.type = 'portrait';
} else {
result.width = targetD;
result.height = targetD;
result.type = 'square';
}
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment