I previously posted a similar question but I don't think I illustrated it very clearly.
If I have a basic responsive image such as <img src="http://www.example.com/nicephoto.jpg">
Let's say that nicephoto.jpg is a large image (4000x5000px). I could load the whole image and let it scale or be cropped by the browser as per its own css or the css of its container - but ideally I would like to ask the server to send me a crop of the image that already fits exactly the size I need. EDIT: My question is not how to do the server side cropping - I've got that covered. My question is as follows:
How can I find out what the maximum width and height of the image is until some of the image will be either cut off or the image will be scaled down? In other words, what is the largest practical size that this image should be?
I could always load a massive grey 10000x10000px placeholder image and then use jQuery's .width() and .height() to figure out how much space it actually takes up, but that is hardly efficient or ideal. Is there some smarter way to do this?
Thanks!
EDIT: I do not have control over what methods will be employed to restrict the maximum height or width of a given image. This code will be running on different sites. One site may use css max-height on the image itself. Another may have a set height for a container. I don't know. Either way I need to figure out how big an image can be shown before it begins to be scaled or cropped.
Setting the late update aside for the moment:
It looks like you want to rescale an image on the server to the exact size needed by the client, rather than using CSS to resize the image in-browser. (Note that "crop" and "rescale" are different things; I'm assuming you actually mean "rescale".)
Here's one way to do what you're trying to do:
You do need, ultimately, to check the container's width and height on the client side -- the container size can't be known until page load, as it depends on the user's viewport size.
You can simplify communication with the server by using the image URL itself as a signal for the desired image to be generated. In this example I construct image URLs for placehold.it; you would instead substitute your own serverside script which would catch the url request, extract the desired width and height from the filename, and return the scaled image.
var reloadImage = function() {
var w = $('.container').width();
var h = $('.container').height();
$('.container img').attr("src", "http://placehold.it/"+w+"x"+h);
};
$('.container').mouseup(reloadImage);
.container {
width: 100px; height: 100px;
border: 2px solid;
resize: both; /* Note that not all browser support "resize"; it's just for demo here, not essential to the technique itself */
display: inline-block;
overflow:auto
}
.container img {width: 100%;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Resize this container:<br>
<div class="container"><img class="image" src="http://placehold.it/100x100"></div>
(Note that there is no need to create a "massive" placeholder image as you suggest -- a single pixel image, CSS scaled to 100% width and height, will do. As will no placeholder image at all, of course.)
Here's why you should not do what you're trying to do:
It will defeat browser-side cacheing of the image (since different images may be needed on each load), effectively increasing bandwidth use rather than saving it.
The time spent serverside re-scaling the image will cost more than would have been saved compared to downloading a larger-than-necessary image (or, alternatively, you'd have to cache many different-sized variations on the image serverside to be handed out as needed.)
Resizing the window after load either triggers new image generation (wasting bandwidth and server time) or leads to potentially undersized images. Upscaled too-small images look significantly worse than downscaled too-large ones.
Here's what you should do instead
Create three or four different sized images each somewhat larger than a typical use case (think desktop, tablet, mobile) and use #media queries to choose one based on the screen size. Use in-browser scaling to tweak that selected image to the exact desired size.
.foo {
background:url('foo_default.png') no-repeat 50% 50% fixed;
background-size: cover;
}
#media only screen and (max-width: 400px) {
.foo { background-image: url('foo_small.png'); }
}
#media only screen and (max-width: 800px) {
.foo { background-image: url('foo_med.png'); }
}
#media only screen and (min-width: 800px) {
.foo { background-image: url('foo_large.png'); }
}
But wait, there's an update
I do not have control over what methods will be employed to restrict the maximum height or width of a given image. This code will be running on different sites. One site may use css max-height on the image itself. Another may have a set height for a container. I don't know. Either way I need to figure out how big an image can be shown before it begins to be scaled or cropped.
This complicates things quite a bit more -- now you not only need to detect on the clientside the container width and height, but also need to parse any client CSS that may be affecting the image and altering its displayed size.
You could use window.getComputedStyle() on the image to get the list of applicable CSS rules; determining their effects would be... somewhat complicated. There is a partial implementation of this in an answer to this question, for example, though it only includes a tiny handful of the CSS rules that could affect an image or background image's size -- for a general-purpose solution you'd basically be doing the same work that the browser does to lays out the image in the first place.
It may go without saying that it'd be simpler to just have each site just request an appropriately-sized image in the first place.
You can do this by submitting an ajax request on document request, as well as on resize.
Then store this information to a session. Then return the scaled image via PHP ie:
<img src="image.php?img=someimg.jpg" />
You said you have server side covered so the javascript would look something like this:
$(function() {
function getvp() {
var vp = {
width: $(window).width(),
height: $(window).height()
}
return vp;
}
function submit_vp(vp) {
$.ajax({
method: "POST",
url: "some.php",
data: { vpwidth: vp.width, vpheight: vp.height }
})
.done(function(msg) {
//ajax is done
alert('width: ' + vp.width + ' height: ' + vp.height);
});
}
//Get initial viewport.
$(document).ready(function() {
submit_vp(getvp());
});
//Resubmit viewport on resize.
$(window).resize(function() {
submit_vp(getvp());
});
});
So if I am understanding correctly, you are looking to take an image, and have it resize based on the height and width of the window is that correct?
Check out the JSFiddle I created as an example using % for the height and width. As well as using the background-size: tag, you can select cover or content.
HTML:
<body>
<div class="box1">
<span></span>
</div>
</body>
CSS:
html, body {
height: 100%;
}
.box1 {
background: url(http://cdn.wallpapersafari.com/23/44/2mYJfU.jpg) no-repeat;
height: 100%;
width: 100%;
background-size: cover;
}
This may be a good refrence: CSS3 Background-size
If I'm understanding correctly, you want to be able to find the area for a picture, then scale it using server side (GD Library?) scripting, then display the image?
This is to save bandwidth?
I would probably just use a jquery call to find the width of the screen (or a container if you give the container padding), then with AJAX, send the width dimension to your back-end script.
The back-end script would then find out the aspect ratio of the image in question, apply the multiple of the w:h ratio to the width of the returned number and the ratio of the picture, then scale the image to that size and send it back.
html
<div class="container">
</div>
javascript
var width = $('.container').width();
$.post("back-end-script.php", {width:width}, function(data){
console.log(data); //Do something here with the returned picture
});
graphic backend script (back-end-script.php)
$width = $_POST['width'];
$img = thisimage.jpg;
//Not sure what script you're using, but this is where you'd find the
//img width and height
$img_w = /*image width*/
$img_h = /*image height*/
$img_r = $img_h / $img_w; //This will get a percentage
$new_img_w = $width;
$new_img_h = $new_img_w * $img_r; //This will make the height the right size
/* Then from here, convert your image to the right size and echo it back */
echo $new_img;
Some downfalls of doing it this way: If someone happens to resize their browser, you either have to run a delayed call to get a new image or you'll be stuck with the wrong sized image. Also, you might save more bandwidth if you just came up with 6-10 different image sizes for a responsive web:
<picture class="n-column-image-above__image tnt tnt-image">
<!--[if IE 9]>
<video style="display: none;">
<![endif]-->
<source media="(min-width: 1144px)" srcset="../img/img_retailer_icon_1077.png, ../img/img_retailer_icon_2154.png 2x"/>
<source media="(min-width: 768px)" srcset="../img/img_retailer_icon_707.png, ../img/img_retailer_icon_1414.png 2x"/>
<source media="(min-width: 375px)" srcset="../img/img_retailer_icon_340.png, ../img/img_retailer_icon_680.png 2x"/>
<source srcset="../img/img_retailer_icon_290.png, ../img/img_retailer_icon_580.png 2x"/>
<!--[if IE 9]>
</video>
<![endif]-->
<img src="../img/img_retailer_icon_1077.png" alt="REPLACE WITH IMAGE DESCRIPTION"/>
</picture>
Related
I recently started experimenting with bootstrap and scaling things to size when the screen is shrunk. If I have an image that needs to be at least 300px to be readable but the screen is only 250px wide (just for example) they would have to scroll left and right to see the whole image. On ford.com they actually swap the larger image out for a similar image that is smaller, more fit for the screen. Then as you drag the screen larger, it switches back to the larger image. Im assuming this has to do with some form of JS and screen size dimensions. Any thoughts?
Technically the feature you're describing could be achieved through either css, html or javascript.
In CSS you can use media queries to load your images through the background property,
.image {
background: url("image.jpg");
}
#media only screen and (max-width: 250px) {
.image {
background: url("alternative-image.jpg");
}
}
or, in case you had both images loaded in the html document, through the display property.
.image {
display: initial;
}
.alternative-image {
display: none;
}
#media only screen and (max-width: 250px) {
.image {
display: none;
}
.alternative-image {
display: initial;
}
}
Read more about media queries here.
In HTML you can use the picture and source elements,
<picture>
<source media="(min-width: 250px)" srcset="image.jpg" />
<img src="alternative-image.jpg" />
</picture>
or the simpler alternative, the srcset attribute.
<img src="alternative-image.jpg" srcset="image.jpg 250px" />
Read more about it here.
Finally, in JavaScript you can use the window size properties to build a function that loads the right image for each size every time the window is resized.
window.onresize = function () {
if (window.innerWidth < 250) {
image.setAttribute("src", "alternative-image.jpg");
} else {
image.setAttribute("src", "image.jpg");
}
}
Read a bit about the window size properties here.
PS. Do NOT directly use these examples, as they are incomplete and unoptimized. Their only purpose is to mock the use of the resources they reference.
this can be archive in 2 ways.
there is a class in bootstrap V3 img-responsive if you add this class in image tag then it will auto resize when viewport is smaller then image size. Reference : http://getbootstrap.com/css/#images-responsive
OR you can use srcset attribute of image tag
example:
<img src="small.jpg" srcset="medium.jpg 1000w, large.jpg 2000w" alt="yah">
in above example you can set image path in srcset in first parameter and on second is image width. in this Browser auto detect viewport width and based on that it will load image.
I working on a responsive design.
If i load the image with the image tag i have no problem with the size, but then it will load on screen too even if i set display:none. This cause loading problems on smartphone devices...
This way i trying to scale it with background-size:contain, but the problem is i have to add an height for the container.
That means if i have a device with different width the image doesn´t fit more.The same problem with background-size:cover. The image flow over if i change width.
Would do it just with css, because there are many pictures and this cause loading problems with javascript.
#header {
width: 100%;
background-image:url(../images/backgrounds/Header_phone2.jpg);
background-size:contain;
background-repeat:no-repeat;
min-height: 200px;
}
Edit
My solution with JS in the answer, improvement tipps are welcome
I made now something, what is working nice for me.
I´m not really good with jquery, this way i´m looking forward for improvement tipps.
Html:
container in container ...
Css stay almost same:
#header {
height:auto;
}
#header-image{
width: 100%;
min-height: 155px;
background-image:url(../bilder/backgrounds/Header_phone2.jpg);
background-size:cover;
background-repeat:no-repeat;
}
Jquery:
if ($( window ).width() <= 966) {
var screenwidth = $(window).width();
var heightimage = (screenwidth /940) * 198;
$("#header-image").css("height", heightimage);
}
$(window).resize(function() {
if ($( window ).width() <= 966) {
var screenwidth = $(window).width();
var heightimage = (screenwidth /940) * 198;
$("#header-image").css("height", heightimage);
}
});
This is working fantastic !! Same like you add the image with img tag and the image doesn´t load with screen design. (look there)
If javascript disabled set min-heigth, like this the image is displayed too.
With jquery i calculate the height of the image. For this i take the width from the display, divide it trough image width and multiply it with height from image. => the correct height for the container.
With the windows-resize function you can change the size of the window and it still works.
This is very simple and works nice for me.
Click for Jsfiddle.
If you use the js script where you delete the src path from img tag, then it will send a request too. With this variant you don´t have problems, look out first link.
Some skilled guys could improve this: select the image width and height with jquery and make a function.
I have a website that contains a side bar and sometimes an image of a very large size (about 800 pixels wide) but I scripted the code so that if a screen resolution is too small, the image shrinks and scales into the small space perfectly according to multiple browsers I tested the site on. I tested the site with the demo version of sortsite by powermapper at:
http://try.powermapper.com/Demo/
It then goes on to complain that "Omitting IMG WIDTH or HEIGHT attributes means page text jumps about as images load. Usability.gov 14:3"
I understand that and I try to include those attributes, the image does not scale correctly.
This is the CSS I use on the image itself to scale it if I had a monitor with a max screen width of 800 pixels:
#media screen and (max-width: 600px){#X IMG{width: 100%}}
I specify 600px because I reserved 200 pixels for the sidebar.
I don't think javascript will be an answer because during the page load, the image placeholder will jump to the new size, and if I placed the code near the beginning, it will delay the the rest of the page from loading somewhat.
I was also thinking using div tags and setting the background to the image, but the problem there is that users won't be able to save it and the rest of the images on my site are part of a CSS sprite sheet.
I also am looking for a solution that will work with as many web browsers as possible even if javascript is disabled.
Any ideas for an answer?
This rule, while correct, went out the window when responsive design came into being:
Omitting IMG WIDTH or HEIGHT attributes means page text jumps about
as images load. Usability.gov 14:3
If you're always going to be using a given aspect ratio, then you can set up your code as below. If you set your width and height attributes on your img tag and you set max-width: 100% (or similar) in your CSS, as people often do when developing responsive sites, then your text will still jump around when the image loads, because it's initial height will be what you specify in your markup, and then when the image loads, the browser will maintain the aspect ratio required for max-width: 100% to work and end up shrinking the height - so that doesn't really help you adhere to your usability rule either.
.img {
background-size: cover;
background: center no-repeat;
}
.ar {
height:0;
padding: 0 0 56.25% /* 16:9 aspect ratio */
}
<div class="img" style="background-image: url(https://placekitten.com/g/500/500);">
<div class="ar"></div>
</div>
Try setting the width and height and then just adjusting width and height with your media queries (rather than max-width and percent width). You shouldn't encounter any scaling problems then.
#media screen and (max-width: 600px){#X IMG{width: 100%}}
This means that IMG will have full width of it's first parent. That parent might not be X element. Are you sure you want that?
Example:
<div id='X'>
<div><div><div><div>
<img src=''>
</div></div></div></div>
</div>
If you are trying to fix x:y img ratio that put height:auto; after width:100%;
Calculate width or height and always use auto for other property to preserve image scaling.
I am building a responsive site using bootstrap 3 & I need a photo gallery on it. The client want to update the gallery themselves..
My issue is the images that they upload can be of any size & any proportion.. How can I make the image fit a certain size div?
Requirements (must work similar to background-size:cover):
-images must keep their original proportions (can be cropped to fit the div)
-images must be stretched/shrunk to fit the FULL div (no white space)
-image must be centered vertically & horizontally in the div
I know I can do something like this but I need it to work more like "background-size:cover":
.myImages {
height:300px;
width:300px;
overflow:hidden;
}
http://jsfiddle.net/w4xTN/1/
EXAMPLE:
You can see at the link below that I have used "background-image:cover" for the "featured properties" photos.. I need to do something similar for normal images (unless someone knows of an image gallery that will support "background-image:cover" for the images?):
http://new.amberlee.com.au/for-sale/browse-for-sales
NOTE: JQuery/Javasript is OK to use & resizing them on upload is not an option ;)
You've got your tag within the .myImages so you need to add properties for your tag hence:
.myImages > img {
height: 100%;
width: 100%;
}
If you want to center the img, just change the height or width attribute to "auto";
you could also hack the img tag to center vertically whereby the image is cropped with playing with the vertical margin:
e.g.
margin-top: -33%;
http://jsfiddle.net/denistsoi/rLmxL/1/
No, you can't get it quite like background-size:cover but..
This approach is pretty damn close: it uses javascript to determine if the image is long or tall and applies styles acordingly.
JS
$('.myImages img').load(function () {
var height = $(this).height();
var width = $(this).width();
console.log('widthandheight:', width, height);
if (width > height) {
$(this).addClass('wide-img');
}
else {
$(this).addClass('tall-img');
}
});
CSS
.tall-img{
margin-top:-50%;
width:100%;
}
.wide-img{
margin-left:-50%;
height:100%;
}
http://jsfiddle.net/b3PbT/
Edit: this is a shameless repost from your last question ;)
I am using image slider specified at: here
My images are of different sizes and I want to set the width and height of the image using following code:
<img src='77.png' width="20px" height="20px" />
But this doesnt work.
I am preety new to javascript, any help will be greatly approciated!
I really don't think this code can handle it (perhaps with a very serious overhaul of the javascript). I set up a fiddle here: http://jsfiddle.net/JLjCP/9/ and in examining what it is doing, it simply does not care what size the image itself is nor does it care if you have resized the image explicitly through the width and height properties. It is only taking the referenced image file and using it as a repositioned background image for the split components which are purely sized by the width and height of the display and the number of sections you tell it to do it in.
So the short answer is this code will not do what you want it to do.
put this in your css :
.cs-coin-slider
{
/*i think the class name is depend on what you set*/
-o-background-size: 20px 20px;
-webkit-background-size: 20px 20px;
-khtml-background-size: 20px 20px;
-moz-background-size: 20px 20px;
background-size: 20px 20px;
}
if you insist to use this coin-slider, no matter you set the size in html or set the css width+height of the image, it wont resized because this plugin treats the image as background..and that css3 background resize that is the only way that save you :)
The documentation on that page says that you can pass size options to the constructor:
$('#coin-slider').coinslider({ width: 20, height: 20 });
If you have different sized images in the same slideshow and you want to change the slider's size dynamically, it might not be possible. Use same sized images or tweak the CSS so that you get black bars around smaller images or something to that effect.
Please post your complete HTML/JS source code, the image size shouldn't matter as long as they are the same height/width as the container of the slideshow. Chances are you are possibly calling the plugin in the wrong way in your JS.