I’m interested in finding the most elegant and ‘correct’ solution to this problem. I’m new to JS/PHP and I’m really excited to be working with it. The goal is to compare the size of a given image to the size of a ‘frame’ for the image (going to be a <div> or <li> eventually) and resize the image accordingly. Users will be uploading images of many sizes and shapes and there are going to be many sizes and shapes of frames. The goal is to make sure that any given image will be correctly resized to fit any given frame. Final implementation will be in PHP, but I’m working out the logic in JS. Here’s what I have:
//predefined variables generated dynamically from other parts of script, these are example values showing the 'landscape in landscape' ratio issue
var $imageHeight = 150, $imageWidth = 310, $height = 240, $width = 300;
//check image orientation
if ( $imageHeight == $imageWidth ) {
var $imageType = 1; // square image
} else if ( $imageHeight > $imageWidth ) {
var $imageType = 2; // portrait image
} else {
var $imageType = 3; // landscape image
};
//check frame orientation and compare to image orientation
if ( $height == $width) { //square frame
if ( ( $imageType === 1 ) || ( $imageType === 3 ) ) {
$deferToHeight = true;
} else {
$deferToHeight = false;
};
} else if ( $height > $width ) { //portrait frame
if ( ( $imageType === 1 ) || ( $imageType === 3 ) ) {
$deferToHeight = true;
} else {
if (($imageHeight / $height) < 1) {
$deferToHeight = true;
} else {
$deferToHeight = false;
};
};
} else { //landscape frame
if ( ( $imageType === 1 ) || ( $imageType === 2 ) ) {
$deferToHeight = false;
} else {
if (($imageWidth / $width) > 1) {
$deferToHeight = true;
} else {
$deferToHeight = false;
};
};
};
//set values to match (null value scales proportionately)
if ($deferToHeight == true) { //defer image size to height of frame
$imageWidth = null;
$imageHeight = $height;
} else { //defer image size to width of frame
$imageWidth = $width;
$imageHeight = null;
};
I’ve tested it with a bunch of different values and it works, but I have a suspicion that I could have implemented a much more elegant solution. What could I have done better?
Here’s how I dealt with this exact problem recently, in a JS implementation:
Much less code than your version. Note that the square case is dealt with either way, which might be true in your version as well.