Resize image with jQuery
The scenario:
I’m building a website, which will not Host the images in its own server. Instead it will reference images from other servers.
Example: The website is hosted at www.mywebsite.com, and the html of the images will be something like <img src=”http://www.otherwebsite.com” />
.
The images from the other servers will be already compressed, so they won’t be very heavy… although they wi开发者_开发知识库ll have around 25KB each, with 500x375 pixels.
The objective:
I want to resize them on the client side, with the help of jQuery. So they became thumbnails.
There are two sizes of thumbnails: 310x140 and 80x80 pixels.
However, not only I want to resize them, has I probably would want them to be zoomed. Because if the original image is only 260px wide, that means that the image would need to be zoomed and then “cropped”, so it would fill the full 310px instead of leaving an empty space on the sides.
I know that I am being too demanding. But I thought that this was a “common” situation that many of you may had dealt with already… so maybe there is some sort of plugin that would do this.
I also know that this means that the user is loading images “heavier” than they are needed, because if they already had 310x140 before loading (which is the thumbnail size), they would be much lighter… but hey! It isn’t my fault that the project was built this way.
The research:
I did found something that almost did what I wanted, with the exception of the “zooming”. You can check by clicking here: http://joanpiedra.com/jquery/thumbs/.
you can easily do it by maintaining the aspect ratio.
define max width and max height.
by maintaining aspect ratio resize them.
if ((h / w) < (maxH / maxW)) {
$img.css('height', '');
$mg.css('width', maxW);
}
else {
$Img.css('height', maxH);
$Img.css('width', '');
精彩评论