Proportional resize images in a fixed block - javascript

I have 3 random images and one fixed block (200x300px).
Please, help me to write an algoritm, I need to change image size proportionally to get into fixed block.
Images width must be equal of block width
http://jsfiddle.net/U8AAu/2/
var images = [
getRandSizes(),
getRandSizes(),
getRandSizes()
];
var sizes = getProportionalSizes(200, 300, images);
$.each(sizes, function(i, size){
var $img = $("<div>", {
class: 'img',
width: size[0],
height: size[1]
}).appendTo('.fixed-block')
});
// todo:
function getProportionalSizes(maxWidth, maxHeight, sizes){
return sizes;
}
function getRandSizes(){
return [getRand(100,200), getRand(100,200)]
}
function getRand(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}

Always changing the image width to fill the box width will cause aspect ratio issues, and will distort your pictures. I would recommend doing something like this.
var image1 = new Object( );
var sizeArray = getRandSizes( );
image1.width = sizeArray[0];
image1.height = sizeArray[1]; //Repeat for images 2 and 3
var images =
[
image1,
image2,
image3
];
images = getProportionalSizes( 200, 300, images );
images.forEach( function( image )
{
var $img = $("<div>",
{
class: 'img',
width: image.width,
height: image.height
}).appendTo('.fixed-block')
});
function getProportionalSizes(maxWidth, maxHeight, images)
{
var totalHeight;
images.forEach( function( image )
{
totalHeight += image.height;
});
images.forEach( function( image )
{
var ratio = image.height / totalHeight;
image.height *= ratio;
image.width *= ratio; //This will ensure that images maintain aspect ratio, but that the total height of the 3 images matches the container height.
});
return images;
}
function getRandSizes()
{
return [getRand(100,200), getRand(100,200)]
}
function getRand(min, max)
{
return Math.floor(Math.random() * (max - min + 1)) + min;
}
EDIT ------------------------
If having full block width is a requirement, and the distortion of the images is irrelevant, then do this instead.
function getProportionalSizes(maxWidth, maxHeight, images)
{
var totalHeight;
images.forEach( function( image )
{
totalHeight += image.height;
});
images.forEach( function( image )
{
var ratio = image.height / totalHeight;
image.height *= ratio;
image.width = maxWidth //This will keep the individual image height proportional to each other, but stretch the picture in the x-direction to fill the block.
});
return images;
}

To change the width of the image to a fixed block width of 200, change your size definition to:
width: 200,
height: size[1]*200/size[0]
This will preserve the aspect ratio while resizing the image to the proper width.
Note that it is possible that the resulting image will be taller than the height specified. If the original image is 100x200, the resulting resized image will be 200x400. This is unavoidable, given the problem constraints.

Related

How do I retrieve background size value in Javascript? [duplicate]

is there an easy way to get the final height and width of a background image with Javascript or jQuery even if a background-size property was applied?
I mean, I know I can get the background image url and load it to an Image object and then get the width and height. But it is the size of the source image. If someone scaled it with CSS then the size changed
How can I find its final size?
#edit
it is different from the question marked as similar because it doesnt say how to get the size in pixels if someone changed the background-size
Using getComputedStyle, I've created this script that returns the width and height of a given element's background, in pixels. It works with:
Dimensions (width or height) set to auto, either explicitly or because no specific value was given (width and height default to auto)
Dimensions set to percentage %
Dimensions set to pixels px
Dimensions set to a combination of any of the previous. (i.e width: 100px; height: auto or width: auto; height: 32.4% or height: 100px; width: 2% or width: 21.2%)
background-size set to cover or contain
It works if background-size is set with an external CSS file, inline CSS, inline header CSS or if it is not set at all (meaning width and height are auto).
Here's a JsFiddle (with cover example)
http://jsfiddle.net/gp4e9d3z/3/
And here's StackOverflow's code snippet (with percentage auto units)
function getBackgroundSize(elem) {
// This:
// * Gets elem computed styles:
// - CSS background-size
// - element's width and height
// * Extracts background URL
var computedStyle = getComputedStyle(elem),
image = new Image(),
src = computedStyle.backgroundImage.replace(/url\((['"])?(.*?)\1\)/gi, '$2'),
cssSize = computedStyle.backgroundSize,
elemW = parseInt(computedStyle.width.replace('px', ''), 10),
elemH = parseInt(computedStyle.height.replace('px', ''), 10),
elemDim = [elemW, elemH],
computedDim = [],
ratio;
// Load the image with the extracted URL.
// Should be in cache already.
image.src = src;
// Determine the 'ratio'
ratio = image.width > image.height ? image.width / image.height : image.height / image.width;
// Split background-size properties into array
cssSize = cssSize.split(' ');
// First property is width. It is always set to something.
computedDim[0] = cssSize[0];
// If height not set, set it to auto
computedDim[1] = cssSize.length > 1 ? cssSize[1] : 'auto';
if(cssSize[0] === 'cover') {
// Width is greater than height
if(elemDim[0] > elemDim[1]) {
// Elem's ratio greater than or equal to img ratio
if(elemDim[0] / elemDim[1] >= ratio) {
computedDim[0] = elemDim[0];
computedDim[1] = 'auto';
} else {
computedDim[0] = 'auto';
computedDim[1] = elemDim[1];
}
} else {
computedDim[0] = 'auto';
computedDim[1] = elemDim[1];
}
} else if(cssSize[0] === 'contain') {
// Width is less than height
if(elemDim[0] < elemDim[1]) {
computedDim[0] = elemDim[0];
computedDim[1] = 'auto';
} else {
// elem's ratio is greater than or equal to img ratio
if(elemDim[0] / elemDim[1] >= ratio) {
computedDim[0] = 'auto';
computedDim[1] = elemDim[1];
} else {
computedDim[1] = 'auto';
computedDim[0] = elemDim[0];
}
}
} else {
// If not 'cover' or 'contain', loop through the values
for(var i = cssSize.length; i--;) {
// Check if values are in pixels or in percentage
if (cssSize[i].indexOf('px') > -1) {
// If in pixels, just remove the 'px' to get the value
computedDim[i] = cssSize[i].replace('px', '');
} else if (cssSize[i].indexOf('%') > -1) {
// If percentage, get percentage of elem's dimension
// and assign it to the computed dimension
computedDim[i] = elemDim[i] * (cssSize[i].replace('%', '') / 100);
}
}
}
// If both values are set to auto, return image's
// original width and height
if(computedDim[0] === 'auto' && computedDim[1] === 'auto') {
computedDim[0] = image.width;
computedDim[1] = image.height;
} else {
// Depending on whether width or height is auto,
// calculate the value in pixels of auto.
// ratio in here is just getting proportions.
ratio = computedDim[0] === 'auto' ? image.height / computedDim[1] : image.width / computedDim[0];
computedDim[0] = computedDim[0] === 'auto' ? image.width / ratio : computedDim[0];
computedDim[1] = computedDim[1] === 'auto' ? image.height / ratio : computedDim[1];
}
// Finally, return an object with the width and height of the
// background image.
return {
width: computedDim[0],
height: computedDim[1]
};
}
// Stuff for debugging
function updateData() {
var background = getBackgroundSize(document.body);
document.getElementById('width').innerHTML = background.width + 'px';
document.getElementById('height').innerHTML = background.height + 'px';
document.getElementById('winWidth').innerHTML = getComputedStyle(document.body).width;
document.getElementById('winHeight').innerHTML = getComputedStyle(document.body).height;
}
// Execute onload, so that the background image is already loaded.
window.onload = window.onresize = updateData;
html, body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
body {
background: url('http://hdwallpapersfit.com/wp-content/uploads/2015/03/images-7.jpg');
background-size: 80% auto;
}
div {
background: rgba(0, 0, 0, 0.5);
color: #fff;
}
<div id="data">
Background width: <span id="width"></span>
<br>
Background height: <span id="height"></span>
<hr>
Body width: <span id="winWidth"></span>
<br>
Body height: <span id="winHeight"></span>
</div>
Using the JSFiddle Here, I found that changing the height or width of the container forces the image to be scaled to the largest height or width. Meaning that the measurement of one edge of the background will be equal to one of the dimension of the container. Using this and some proportions we can calculate the dimensions of the image.
// let .container represent element containing the image
var image; // the image object to the background image
var dim_h, dim_w; // the height and width of the actual image
height = $(".container").height();
width = $(".container").width();
if (height >= width)
{
dim_h = height;
dim_w = (height / image.height) * image.width;
}
else
{
dim_w = width;
dim_h = (width / image.width) * image.height;
}
// dim_w and dim_h contain the width and height of the actual
// background image after scaling
The above code uses the proportion below to calculate it.
(element_height / image_height) == (element_width / image_width)
I think it should give you the answer you want.

Resizing image preview not working

Working JSFiddle before attempting to implement: http://jsfiddle.net/qa9m7t33/
After attempting to implement: http://jsfiddle.net/z1k538sm/
I found how to resize an image however I believe this was not an example for being it prior upload and I am pretty new to this. What I believe is wrong is the variable;'
var width = e.target.result.width(); // Current image width
var height = e.target.result.height(); // Current image height
I am also having the problem with centering my text in the upload field.
Updated Fiddle: http://jsfiddle.net/m5jLf259/
Not exactly a Js answer to this but adding a line-height CSS to the element
#file {
line-height: 37px;
}
will get the job done, I guess if you want it to be jQuery you could do
$('#file').css('line-height',$('#file').height() + 'px');
As for the first part of your problem I couldn't make out a question, sorry.
Edit:
for the first part try this:
var wrapper = $('<div/>').css({height:0,width:0,'overflow':'hidden'});
var fileInput = $(':file').wrap(wrapper);
fileInput.change(function(){
readURL(this);
})
$('#file').click(function(){
fileInput.click();
}).show();
function readURL(input) {
$('#blah').hide();
if (input.files && input.files[0]) {
var goUpload = true;
var uploadFile = input.files[0];
if (!(/\.(gif|jpg|jpeg|tiff|png)$/i).test(uploadFile.name)) {
$('#file').effect( "shake" );
$('#file').text('You must select an image file only');
setTimeout(function() { $('#file').text('Choose file');},5000);
goUpload = false;
}
if (uploadFile.size > 2000000) { // 2mb
//common.notifyError('Please upload a smaller image, max size is 2 MB');
$('#file').text('Please upload a smaller image, max size is 2 MB');
setTimeout(function() { $('#file').text('Choose file');},5000);
goUpload = false;
}
if (goUpload) {
$('#file').text("Uploading "+uploadFile.name);
var reader = new FileReader();
reader.onload = function (e) {
var img = new Image;
img.onload = function() {
var maxWidth = 100; // Max width for the image
var maxHeight = 100; // Max height for the image
var ratio = 0; // Used for aspect ratio
var width = this.width; // Current image width
var height = this.height; // Current image height
// Check if the current width is larger than the max
if (width > maxWidth) {
ratio = maxWidth / width; // get ratio for scaling image
$('#blah').css("width", maxWidth); // Set new width
$('#blah').css("height", height * ratio); // Scale height based on ratio
height = height * ratio; // Reset height to match scaled image
}
// Check if current height is larger than max
if (height > maxHeight) {
ratio = maxHeight / height; // get ratio for scaling image
$('#blah').css("height", maxHeight); // Set new height
$('#blah').css("width", width * ratio); // Scale width based on ratio
width = width * ratio; // Reset width to match scaled image
}
$('#blah').attr('src', this.src).show();
$('#file').text(uploadFile.name);
};
img.src = reader.result;
}
reader.readAsDataURL(uploadFile);
}
}
}
You shouldn't have the part where it says:
47 var width = uploadFile.width(); // Current image width
48 var height = uploadFile.height(); // Current image height
twice because you're just undoing your work from the previous IF.
Also it seems the FileReader() is unable to get the image size properties so instead have FileReader, create an image Object, and then make the image Object's onload do all the work.

jQuery jslint var was used before it was defined

I've been using jslint to try see what it says about my code, and i get lots of flags, but i am working through trying improve it. However i am stuck on the error
maxHeight was used before it was defined
My jQuery:
$.fn.thumbSizr = function () { // begin function
"use strict";
return this.each(function () {
var $this = $(this);
maxWidth = $(this).parent().width(); // Max width for the image
minHeight = $(this).parent().height(); // Max height for the image
ratio = 0; // Used for aspect ratio
width = $(this).width(); // Current image width
height = $(this).height(); // Current image height
if(width > maxWidth){
ratio = maxWidth / width; // get ratio for scaling image
$(this).css("width", maxWidth); // Set new width
$(this).css("height", height * ratio); // Scale height based on ratio
height = height * ratio; // Reset height to match scaled image
width = width * ratio; // Reset width to match scaled image
}
// Check if current height is larger than max
if(height < minHeight){
ratio = minHeight / height; // get ratio for scaling image
$(this).css("height", minHeight); // Set new height
$(this).css("width", width * ratio); // Scale width based on ratio
width = width * ratio; // Reset width to match scaled image
}
var $img = $(this),
css = {
position: 'absolute',
marginLeft: '-' + (parseInt( $img.css('width') ) / 2) + 'px',
left: '50%',
top: '50%',
marginTop: '-' + (parseInt( $img.css('height') ) / 2) + 'px'
};
$img.css( css );
});
};
I'm no jQuery pro so this might be ropey but i really wanted to make it as good as possible. Can anyone explain and suggest why i am getting this message and how to avoid it in the future?
Thanks
You are using semicolon instead of comma when declaring multiple variable with single "var"
This part is wrong:
var $this = $(this);
maxWidth = $(this).parent().width(); // Max width for the image
minHeight = $(this).parent().height(); // Max height for the image
ratio = 0; // Used for aspect ratio
width = $(this).width(); // Current image width
height = $(this).height(); // Current image height
fixed:
var $this = $(this),
maxWidth = $(this).parent().width(), // Max width for the image
minHeight = $(this).parent().height(), // Max height for the image
ratio = 0, // Used for aspect ratio
width = $(this).width(), // Current image width
height = $(this).height(); // Current image height

How to resize images proportionally / keeping the aspect ratio?

I have images that will be quite big in dimension and I want to shrink them down with jQuery while keeping the proportions constrained, i.e. the same aspect ratio.
Can someone point me to some code, or explain the logic?
I think this is a really cool method:
/**
* Conserve aspect ratio of the original region. Useful when shrinking/enlarging
* images to fit into a certain area.
*
* #param {Number} srcWidth width of source image
* #param {Number} srcHeight height of source image
* #param {Number} maxWidth maximum available width
* #param {Number} maxHeight maximum available height
* #return {Object} { width, height }
*/
function calculateAspectRatioFit(srcWidth, srcHeight, maxWidth, maxHeight) {
var ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight);
return { width: srcWidth*ratio, height: srcHeight*ratio };
}
Have a look at this piece of code from http://ericjuden.com/2009/07/jquery-image-resize/
$(document).ready(function() {
$('.story-small img').each(function() {
var maxWidth = 100; // Max width for the image
var maxHeight = 100; // Max height for the image
var ratio = 0; // Used for aspect ratio
var width = $(this).width(); // Current image width
var height = $(this).height(); // Current image height
// Check if the current width is larger than the max
if(width > maxWidth){
ratio = maxWidth / width; // get ratio for scaling image
$(this).css("width", maxWidth); // Set new width
$(this).css("height", height * ratio); // Scale height based on ratio
height = height * ratio; // Reset height to match scaled image
width = width * ratio; // Reset width to match scaled image
}
// Check if current height is larger than max
if(height > maxHeight){
ratio = maxHeight / height; // get ratio for scaling image
$(this).css("height", maxHeight); // Set new height
$(this).css("width", width * ratio); // Scale width based on ratio
width = width * ratio; // Reset width to match scaled image
height = height * ratio; // Reset height to match scaled image
}
});
});
If I understand the question correctly, you don't even need jQuery for this. Shrinking the image proportionally on the client can be done with CSS alone: just set its max-width and max-height to 100%.
<div style="height: 100px">
<img src="http://www.getdigital.de/images/produkte/t4/t4_css_sucks2.jpg"
style="max-height: 100%; max-width: 100%">
</div>​
Here's the fiddle: http://jsfiddle.net/9EQ5c/
In order to determine the aspect ratio, you need to have a ratio to aim for.
function getHeight(length, ratio) {
var height = ((length)/(Math.sqrt((Math.pow(ratio, 2)+1))));
return Math.round(height);
}
function getWidth(length, ratio) {
var width = ((length)/(Math.sqrt((1)/(Math.pow(ratio, 2)+1))));
return Math.round(width);
}
In this example I use 16:10 since this the typical monitor aspect ratio.
var ratio = (16/10);
var height = getHeight(300,ratio);
var width = getWidth(height,ratio);
console.log(height);
console.log(width);
Results from above would be 147 and 300
There are 4 parameters to this problem
current image width iX
current image height iY
target viewport width cX
target viewport height cY
And there are 3 different conditional parameters
cX > cY ?
iX > cX ?
iY > cY ?
solution
Find the smaller side of the target view port F
Find the larger side of the current view port L
Find the factor of both F/L = factor
Multiply both sides of the current port with the factor ie, fX = iX * factor; fY = iY * factor
that's all you need to do.
//Pseudo code
iX;//current width of image in the client
iY;//current height of image in the client
cX;//configured width
cY;//configured height
fX;//final width
fY;//final height
1. check if iX,iY,cX,cY values are >0 and all values are not empty or not junk
2. lE = iX > iY ? iX: iY; //long edge
3. if ( cX < cY )
then
4. factor = cX/lE;
else
5. factor = cY/lE;
6. fX = iX * factor ; fY = iY * factor ;
This is a mature forum, I am not giving you code for that :)
actually i have just run into this problem and the solution I found was strangely simple and weird
$("#someimage").css({height:<some new height>})
and miraculously the image is resized to the new height and conserving the same ratio!
Does <img src="/path/to/pic.jpg" style="max-width:XXXpx; max-height:YYYpx;" > help?
Browser will take care of keeping aspect ratio intact.
i.e max-width kicks in when image width is greater than height and its height will be calculated proportionally. Similarly max-height will be in effect when height is greater than width.
You don't need any jQuery or javascript for this.
Supported by ie7+ and other browsers (http://caniuse.com/minmaxwh).
If the image is proportionate then this code will fill the wrapper with image. If image is not in proportion then extra width/height will get cropped.
<script type="text/javascript">
$(function(){
$('#slider img').each(function(){
var ReqWidth = 1000; // Max width for the image
var ReqHeight = 300; // Max height for the image
var width = $(this).width(); // Current image width
var height = $(this).height(); // Current image height
// Check if the current width is larger than the max
if (width > height && height < ReqHeight) {
$(this).css("min-height", ReqHeight); // Set new height
}
else
if (width > height && width < ReqWidth) {
$(this).css("min-width", ReqWidth); // Set new width
}
else
if (width > height && width > ReqWidth) {
$(this).css("max-width", ReqWidth); // Set new width
}
else
(height > width && width < ReqWidth)
{
$(this).css("min-width", ReqWidth); // Set new width
}
});
});
</script>
This should work for images with all possible proportions
$(document).ready(function() {
$('.list img').each(function() {
var maxWidth = 100;
var maxHeight = 100;
var width = $(this).width();
var height = $(this).height();
var ratioW = maxWidth / width; // Width ratio
var ratioH = maxHeight / height; // Height ratio
// If height ratio is bigger then we need to scale height
if(ratioH > ratioW){
$(this).css("width", maxWidth);
$(this).css("height", height * ratioW); // Scale height according to width ratio
}
else{ // otherwise we scale width
$(this).css("height", maxHeight);
$(this).css("width", height * ratioH); // according to height ratio
}
});
});
Here's a correction to Mehdiway's answer. The new width and/or height were not being set to the max value. A good test case is the following (1768 x 1075 pixels): http://spacecoastsports.com/wp-content/uploads/2014/06/sportsballs1.png. (I wasn't able to comment on it above due to lack of reputation points.)
// Make sure image doesn't exceed 100x100 pixels
// note: takes jQuery img object not HTML: so width is a function
// not a property.
function resize_image (image) {
var maxWidth = 100; // Max width for the image
var maxHeight = 100; // Max height for the image
var ratio = 0; // Used for aspect ratio
// Get current dimensions
var width = image.width()
var height = image.height();
console.log("dimensions: " + width + "x" + height);
// If the current width is larger than the max, scale height
// to ratio of max width to current and then set width to max.
if (width > maxWidth) {
console.log("Shrinking width (and scaling height)")
ratio = maxWidth / width;
height = height * ratio;
width = maxWidth;
image.css("width", width);
image.css("height", height);
console.log("new dimensions: " + width + "x" + height);
}
// If the current height is larger than the max, scale width
// to ratio of max height to current and then set height to max.
if (height > maxHeight) {
console.log("Shrinking height (and scaling width)")
ratio = maxHeight / height;
width = width * ratio;
height = maxHeight;
image.css("width", width);
image.css("height", height);
console.log("new dimensions: " + width + "x" + height);
}
}
$('#productThumb img').each(function() {
var maxWidth = 140; // Max width for the image
var maxHeight = 140; // Max height for the image
var ratio = 0; // Used for aspect ratio
var width = $(this).width(); // Current image width
var height = $(this).height(); // Current image height
// Check if the current width is larger than the max
if(width > height){
height = ( height / width ) * maxHeight;
} else if(height > width){
maxWidth = (width/height)* maxWidth;
}
$(this).css("width", maxWidth); // Set new width
$(this).css("height", maxHeight); // Scale height based on ratio
});
2 Steps:
Step 1) calculate the ratio of the original width / original height of Image.
Step 2) multiply the original_width/original_height ratio by the new desired height to get the new width corresponding to the new height.
Without additional temp-vars or brackets.
var width= $(this).width(), height= $(this).height()
, maxWidth=100, maxHeight= 100;
if(width > maxWidth){
height = Math.floor( maxWidth * height / width );
width = maxWidth
}
if(height > maxHeight){
width = Math.floor( maxHeight * width / height );
height = maxHeight;
}
Keep in Mind: Search engines don't like it, if width and height attribute does not fit the image, but they don't know JS.
After some trial and error I came to this solution:
function center(img) {
var div = img.parentNode;
var divW = parseInt(div.style.width);
var divH = parseInt(div.style.height);
var srcW = img.width;
var srcH = img.height;
var ratio = Math.min(divW/srcW, divH/srcH);
var newW = img.width * ratio;
var newH = img.height * ratio;
img.style.width = newW + "px";
img.style.height = newH + "px";
img.style.marginTop = (divH-newH)/2 + "px";
img.style.marginLeft = (divW-newW)/2 + "px";
}
The resize can be achieved(maintaining aspect ratio) using CSS.
This is a further simplified answer inspired by Dan Dascalescu's post.
http://jsbin.com/viqare
img{
max-width:200px;
/*Or define max-height*/
}
<img src="http://e1.365dm.com/13/07/4-3/20/alastair-cook-ashes-profile_2967773.jpg" alt="Alastair Cook" />
<img src="http://e1.365dm.com/13/07/4-3/20/usman-khawaja-australia-profile_2974601.jpg" alt="Usman Khawaja"/>
This issue can be solved by CSS.
.image{
max-width:*px;
}
Resize to fit the container, get scale factor, scale down percentage control
$(function () {
let ParentHeight = 200;
let ParentWidth = 300;
$("#Parent").width(ParentWidth).height(ParentHeight);
$("#ParentHeight").html(ParentHeight);
$("#ParentWidth").html(ParentWidth);
var RatioOfParent = ParentHeight / ParentWidth;
$("#ParentAspectRatio").html(RatioOfParent);
let ChildHeight = 2000;
let ChildWidth = 4000;
var RatioOfChild = ChildHeight / ChildWidth;
$("#ChildAspectRatio").html(RatioOfChild);
let ScaleHeight = ParentHeight / ChildHeight;
let ScaleWidth = ParentWidth / ChildWidth;
let Scale = Math.min(ScaleHeight, ScaleWidth);
$("#ScaleFactor").html(Scale);
// old scale
//ChildHeight = ChildHeight * Scale;
//ChildWidth = ChildWidth * Scale;
// reduce scale by 10%, you can change the percentage
let ScaleDownPercentage = 10;
let CalculatedScaleValue = Scale * (ScaleDownPercentage / 100);
$("#CalculatedScaleValue").html(CalculatedScaleValue);
// new scale
let NewScale = (Scale - CalculatedScaleValue);
ChildHeight = ChildHeight * NewScale;
ChildWidth = ChildWidth * NewScale;
$("#Child").width(ChildWidth).height(ChildHeight);
$("#ChildHeight").html(ChildHeight);
$("#ChildWidth").html(ChildWidth);
});
#Parent {
background-color: grey;
}
#Child {
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="Parent">
<div id="Child"></div>
</div>
<table>
<tr>
<td>Parent Aspect Ratio</td>
<td id="ParentAspectRatio"></td>
</tr>
<tr>
<td>Child Aspect Ratio</td>
<td id="ChildAspectRatio"></td>
</tr>
<tr>
<td>Scale Factor</td>
<td id="ScaleFactor"></td>
</tr>
<tr>
<td>Calculated Scale Value</td>
<td id="CalculatedScaleValue"></td>
</tr>
<tr>
<td>Parent Height</td>
<td id="ParentHeight"></td>
</tr>
<tr>
<td>Parent Width</td>
<td id="ParentWidth"></td>
</tr>
<tr>
<td>Child Height</td>
<td id="ChildHeight"></td>
</tr>
<tr>
<td>Child Width</td>
<td id="ChildWidth"></td>
</tr>
</table>
Resizing an image to a certain percentage
// scale can be 0.40, 0.80, etc.
function imageScaler(originalHeight, originalWidth, scale) {
const scaledWidth = originalWidth * scale;
const scaledHeight = (originalHeight / originalWidth) * scaledWidth;
return [scaledHeight, scaledWidth];
}
You can determine width height if you want a particular aspect ratio to do so,
Let you have a picture of 3264×2448
Pictures aspect ratio is => 2448 ÷ 3264 =0.75
Now just check number which gives 0.75 on division.
Like: for
16:9 => 9÷16 =0.5625 (wrong it is not 0.75)
Now 4:3 =>3÷4=0.75 (we get it )
So the original aspect ratio is 4:3
now to resize the image just do
Width=3264 ÷/× 4
Height=2448 ÷/× 3
÷ for reducing
× for increasing
Hope you can understand and code yourself this is very effective because we just need to do very basic arithmetic just division or multiplication so simple.
Let me know if i am wrong.
This totally worked for me for a draggable item - aspectRatio:true
.appendTo(divwrapper).resizable({
aspectRatio: true,
handles: 'se',
stop: resizestop
})

Display Image in fixed size div

I've a 100*100 <div> in which I would like to display images of different sizes randomly without stretching them.
Note:The image should appear as origional, just resizing should be done inorder to place it in box
Maybe this style will help you:
div {
position:relative;
}
div img {
max-width:100%;max-height:100%;
}
here's a simple function to calculate your aspect ratio and size the image down. it takes the path to the file and the original width and height of the image. you can provide all that however you see fit. 'myElement' would be the id of your image element.
function loadImage(filename, width, height) {
var aspect = width / height;
var w, h;
if (width > height) {
w = 100;
h = Math.round(100 / aspect);
}
else {
h = 100;
w = Math.round(100 * aspect);
}
var element = document.getElementById('myElement');
element.src = filename;
element.style.width = w + 'px';
element.style.height = h + 'px';
}

Categories

Resources