Как изменить размер изображений пропорционально/сохранить соотношение сторон?
У меня есть изображения, которые будут довольно большими по размеру, и я хочу сжать их с помощью jQuery, сохраняя при этом пропорции с ограничением, т.е. с тем же соотношением сторон.
Может кто-нибудь указать мне на какой-то код или объяснить логику?
Ответы
Ответ 1
Взгляните на этот фрагмент кода 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
}
});
});
Ответ 2
Я думаю, что это действительно классный метод:
/**
* Conserve aspect ratio of the orignal 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 };
}
Ответ 3
Если я правильно понял вопрос, для этого вам даже не нужен jQuery. Сжатие изображения пропорционально на клиенте может выполняться только с помощью CSS: просто установите его max-width
и max-height
на 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>
Здесь скрипка: http://jsfiddle.net/9EQ5c/
Ответ 4
На самом деле, я только что столкнулся с этой проблемой, и решение, которое я нашел, было странно простым и странным
$("#someimage").css({height:<some new height>})
и чудесным образом изображение изменяется на новую высоту и сохраняет одинаковое соотношение!
Ответ 5
Помогает ли <img src="/path/to/pic.jpg" style="max-width:XXXpx; max-height:YYYpx;" >
?
Браузер позаботится о сохранении соотношения сторон.
i.e max-width
срабатывает, когда ширина изображения больше высоты, и его высота будет рассчитываться пропорционально. Аналогично max-height
будет действовать, когда высота больше ширины.
Для этого вам не нужен jQuery или javascript.
Поддерживается ie7 + и другими браузерами (http://caniuse.com/minmaxwh).
Ответ 6
Чтобы определить соотношение сторон вам необходимо иметь отношение к цели.
![Height]()
function getHeight(length, ratio) {
var height = ((length)/(Math.sqrt((Math.pow(ratio, 2)+1))));
return Math.round(height);
}
![Width]()
function getWidth(length, ratio) {
var width = ((length)/(Math.sqrt((1)/(Math.pow(ratio, 2)+1))));
return Math.round(width);
}
В этом примере я использую 16:10
, так как это типичное соотношение сторон монитора.
var ratio = (16/10);
var height = getHeight(300,ratio);
var width = getWidth(height,ratio);
console.log(height);
console.log(width);
Результаты выше были бы 147
и 300
Ответ 7
Для этой проблемы существует 4 параметра
- текущая ширина изображения iX
- высота текущего изображения iY
- целевая ширина видового экрана cX
- целевая высота видового экрана cY
И есть 3 разных условных параметра
- cX > cY?
- iX > cX?
- iY > cY?
решение
- Найдите меньшую сторону порта целевого представления F
- Найдите большую сторону текущего порта просмотра L
- Найдите коэффициент как F/L = коэффициент
- Умножьте обе стороны текущего порта с коэффициентом, т.е. коэффициент fX = iX *; fY = iY * factor
что все, что вам нужно сделать.
//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 ;
Это зрелый форум, я не даю вам код для этого:)
Ответ 8
$('#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
});
Ответ 9
Это должно работать для изображений со всеми возможными пропорциями
$(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
}
});
});
Ответ 10
Если изображение пропорционально, то этот код заполнит обертку изображением. Если изображение не пропорционально, добавляется дополнительная ширина/высота.
<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>
Ответ 11
Без дополнительных temp-vars или 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: поисковым системам это не нравится, если атрибут width и height не соответствует изображению, но они не знают JS.
Ответ 12
После некоторых проб и ошибок я пришел к этому решению:
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";
}
Ответ 13
Изменение размера может быть достигнуто (поддерживая соотношение сторон) с помощью CSS.
Это еще один упрощенный ответ, вдохновленный записью Дэна Даскалеску.
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"/>
Ответ 14
Здесь исправляется ответ Мехдиуэй. Новая ширина и/или высота не были установлены на максимальное значение. Хорошим тестовым примером является следующее (1768 x 1075 пикселей): http://spacecoastsports.com/wp-content/uploads/2014/06/sportsballs1.png. (Я не смог прокомментировать это выше из-за отсутствия точек репутации.)
// 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);
}
}
Ответ 15
Посмотрите на эту пьесу...
/**
* @param {Number} width
* @param {Number} height
* @param {Number} destWidth
* @param {Number} destHeight
*
* @return {width: Number, height:Number}
*/
function resizeKeepingRatio(width, height, destWidth, destHeight)
{
if (!width || !height || width <= 0 || height <= 0)
{
throw "Params error";
}
var ratioW = width / destWidth;
var ratioH = height / destHeight;
if (ratioW <= 1 && ratioH <= 1)
{
var ratio = 1 / ((ratioW > ratioH) ? ratioW : ratioH);
width *= ratio;
height *= ratio;
}
else if (ratioW > 1 && ratioH <= 1)
{
var ratio = 1 / ratioW;
width *= ratio;
height *= ratio;
}
else if (ratioW <= 1 && ratioH > 1)
{
var ratio = 1 / ratioH;
width *= ratio;
height *= ratio;
}
else if (ratioW >= 1 && ratioH >= 1)
{
var ratio = 1 / ((ratioW > ratioH) ? ratioW : ratioH);
width *= ratio;
height *= ratio;
}
return {
width : width,
height : height
};
}
Ответ 16
Это полностью сработало для меня для перетаскиваемого элемента - aspectRatio: true
.appendTo(divwrapper).resizable({
aspectRatio: true,
handles: 'se',
stop: resizestop
})