Is there a way of calculating / estimating what the image size would be depending on the screen resolution before the image has been rendered? I need more logical help rather than code to be honest. What do I need to calculate?
Image size: 800px * 450px
Window size: 424px * 728px
The image works out to be 424px * 239px. I need to calculate this in code so I can adjust positions of other elements following after (absolute / fixed elements).
What I have done so far is;
var ratio1 = (this.retrievedNewsArticle.featuredImage.width / this.retrievedNewsArticle.featuredImage.height);
var ratio2 = ($(window).innerWidth() / this.retrievedNewsArticle.featuredImage.width);
// Ratio 1 = 424
// Ratio 2 = 0.53
So what's next?
It sounds like you already know the image's size, and it sounds like you want the image to be the full width of the window, and just need to know how to determine the height of the image. If so, the target height is the image height times the windows width divided by the image width:
var renderedWidth = imageWidth;
var renderedHeight = imageHeight * (windowWidth / imageWidth);
That maintains the aspect ratio.
That assumes the image is always wider than the screen. Let's remove that assumption.
If you want the image to stretch to fill:
var renderedWidth, renderedHeight;
if (windowWidth >= imageWidth) {
renderedWidth = imageWidth * (windowWidth / imageWidth);
} else {
renderedWidth = imageWidth;
}
renderedHeight = imageHeight * (windowWidth / renderedWidth);
If you don't want the image to stretch to fill:
var renderedWidth, renderedHeight;
if (windowWidth >= imageWidth) {
renderedWidth = imageWidth;
renderedHeight = imageHeight;
} else {
renderedWidth = imageWidth;
renderedHeight = imageHeight * (windowWidth / imageWidth);
}
I have a picture that is bigger than the screen and the user is able to scroll left and right on the image. How do I center the image horizontally using javascript or css?
Here is the view:
<div ng-show="isLandscape">
<div ng-if="isSelected(color.code)" ng-repeat="color in colors">
<img id="fullSwatch" ng-src="{{ images.swatches[color.code] }}" full-swatch>
</div>
</div>
Here is my directive:
colorsController.directive('fullSwatch', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.bind('load', function() {
var img = document.getElementById("fullSwatch");
//swap width and height values because they are before orientation change
var h = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
var w = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
var imageWidth = img.width;
var imageHeight = img.height;
var aspectRatio = imageWidth / imageHeight;
// fill image vertically
imageHeight = h;
imageWidth = h * aspectRatio;
img.style.width = imageWidth + "px";
img.style.height = imageHeight + "px";
img.style.maxWidth = "none";
var container = img.parentNode;
var scrollLeft = (imageWidth - w) / 2;
container.scrollLeft = scrollLeft;
});
}
};
});
I have tried adding scroll left to the parent div and on the image itself, but it is not being applied.
div{
position:relative;
overflow-y:hidden;
}
#fullSwatch{
margin:0 auto;
display:table;
}
I also made a Jsfiddle demo for an example using a Google Image
http://jsfiddle.net/x6jDu/
This approach is pretty simple, where any oversized images bigger than the outter div will be centered with horizontal scrolling.Set margin to 0 auto on the image id does the centering trick. Hope this solves your problem.
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
This is what I need:
The image must completely fill 100% the area the div covers - left to
right and top to bottom.
the image must not be squashed or streched - just be cropped or
must overflow.
The image must be kept as small as possible, so whatever the resize - you
can still see either the very sides OR the very top and bottom.
The div itself will be adjusting in height and width as both are a percentage of the main window.
I have found a little bit of JavaScript here that is manipulating the image just how I want when the window is resized, but is displaying it in the whole window.
<html>
<head>
<title>test</title>
<script type="text/javascript">
function resizeImage()
{
var window_height = document.body.clientHeight
var window_width = document.body.clientWidth
var image_width = document.images[0].width
var image_height = document.images[0].height
var height_ratio = image_height / window_height
var width_ratio = image_width / window_width
if (height_ratio > width_ratio)
{
document.images[0].style.width = "100%"
document.images[0].style.height = "auto"
}
else
{
document.images[0].style.width = "auto"
document.images[0].style.height = "100%"
}
}
</script>
</head>
<body onresize="resizeImage()">
<img onload="resizeImage()" src="f/a.jpg">
</body>
</html>
Here is a demo
Please don't just answer that all I need is:
<img style="width : 100%;">
This is so much more than that.
It's not too easy to explain but check the demo and drag the corner of the window around and that'll be worth 1000 words...!
Can it (or something like it) be made to work the same way within a % sized div?
I wrote a jQuery plugin that does exactly this. Check out my blog post here and the demo here
jQuery.fn.resizeToParent = function(options) {
var defaults = {
parent: 'div'
}
var options = jQuery.extend(defaults, options);
return this.each(function() {
var o = options;
var obj = jQuery(this);
// bind to load of image
obj.load(function() {
// dimensions of the parent
var parentWidth = obj.parents(o.parent).width();
var parentHeight = obj.parents(o.parent).height();
// dimensions of the image
var imageWidth = obj.width();
var imageHeight = obj.height();
// step 1 - calculate the percentage difference between image width and container width
var diff = imageWidth / parentWidth;
// step 2 - if height divided by difference is smaller than container height, resize by height. otherwise resize by width
if ((imageHeight / diff) < parentHeight) {
obj.css({'width': 'auto', 'height': parentHeight});
// set image variables to new dimensions
imageWidth = imageWidth / (imageHeight / parentHeight);
imageHeight = parentHeight;
}
else {
obj.css({'height': 'auto', 'width': parentWidth});
// set image variables to new dimensions
imageWidth = parentWidth;
imageHeight = imageHeight / diff;
}
// step 3 - center image in container
var leftOffset = (imageWidth - parentWidth) / -2;
var topOffset = (imageHeight - parentHeight) / -2;
obj.css({'left': leftOffset, 'top': topOffset});
});
// force ie to run the load function if the image is cached
if (this.complete) {
obj.trigger('load');
}
});
}
And if you want the image to resize when the window is resized, just bind a resize handler to the window:
$(window).resize(function() {
$('img').resizeToParent();
});
Ok I've been playing around with it:
<html>
<head>
<title>test</title>
<style>
#imgarea {
position:absolute;
right:0px;
height:75%;
width:70%;
top:25%;
}
</style>
<script type="text/javascript">
function resizeImage()
{
var window_height = document.body.clientHeight
var window_width = document.body.clientWidth
var image_width = document.images[0].width
var image_height = document.images[0].height
var area_width = window_width * 0.7
var area_height = window_height * 0.75
var height_ratio = image_height / area_height
var width_ratio = image_width / area_width
if (height_ratio > width_ratio)
{
document.images[0].style.width = "100%"
document.images[0].style.height = "auto"
}
else
{
document.images[0].style.width = "auto"
document.images[0].style.height = "100%"
}
}
</script>
</head>
<body onresize="resizeImage()">
<div id="imgarea">
<img onload="resizeImage()" src="f/a.jpg">
</div>
</body>
</html>
It keeps resizing as the div resizes - as mentioned the div is
resizing with the window - this one keeps working seemlesly.
It seems to be OK across IE9, Fire Fox, Oprea, Chrome, and safari
over xp and 7
so really it answers my question perfectly, its just - now i've seen Christian's centering version i wish i had the know-how to make this do it i've tried a few things but am now stuck. Any Ideas?
P.S. if you dont know the width and height % of the div when you right the script i think it could be got with GetElementById - somehow... beyond me though;)
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
})