IT

이미지 크기를 비례 적으로 조정하고 종횡비를 유지하는 방법은 무엇입니까?

lottoking 2020. 6. 14. 10:09
반응형

이미지 크기를 비례 적으로 조정하고 종횡비를 유지하는 방법은 무엇입니까?


나는 크기가 상당히 큰 이미지를 가지고 있으며 비율을 제한된 가로 세로 비율로 유지하면서 jQuery로 이미지를 축소하고 싶습니다.

누군가 나를 코드로 지적하거나 논리를 설명 할 수 있습니까?


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
        }
    });
});

나는 이것이 정말 멋진 방법 이라고 생각합니다 .

 /**
  * 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 };
 }

질문을 올바르게 이해하면 jQuery가 필요하지 않습니다. 클라이언트에 비례하여 이미지를 축소 혼자 CSS로 수행 할 수 있습니다 단지의 설정 max-widthmax-height100%.

<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/


가로 세로 비율 을 결정하려면 목표 비율을 가져야합니다.

신장

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);
}

이 예에서는 이것이 16:10전형적인 모니터 종횡비이므로 사용 합니다.

var ratio = (16/10);
var height = getHeight(300,ratio);
var width = getWidth(height,ratio);

console.log(height);
console.log(width);

위의 결과가 될 것입니다 147300


실제로 나는이 문제에 부딪 쳤고 내가 찾은 해결책은 이상하게 간단하고 이상했다.

$("#someimage").css({height:<some new height>})

기적적으로 이미지는 새로운 높이로 크기가 조정되고 동일한 비율을 유지합니다!


이 문제에는 4 가지 파라미터가 있습니다

  1. 현재 이미지 너비 iX
  2. 현재 이미지 높이 iY
  3. 대상 뷰포트 너비 cX
  4. 대상 뷰포트 높이 cY

그리고 3 가지 조건부 매개 변수가 있습니다

  1. cX> cY?
  2. iX> cX?
  3. iY> cY?

해결책

  1. 대상 뷰 포트 F의 작은 쪽을 찾으십시오
  2. 현재 뷰 포트 L의 큰 쪽을 찾으십시오.
  3. F / L = factor의 인수를 모두 구합니다
  4. 현재 포트의 양쪽에 계수 즉, fX = iX * 계수를 곱하십시오. fY = iY * 계수

그게 당신이해야 할 전부입니다.

//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 ; 

이것은 성숙한 포럼입니다, 나는 당신에게 그 코드를주지 않습니다 :)


합니까의 <img src="/path/to/pic.jpg" style="max-width:XXXpx; max-height:YYYpx;" >도움?

브라우저는 가로 세로 비율을 그대로 유지합니다.

max-width, 이미지 너비가 높이보다 크고 높이가 비례 적으로 계산되면 시작됩니다. max-height높이가 너비보다 큰 경우에도 마찬가지 입니다.

이를 위해 jQuery 또는 자바 스크립트가 필요하지 않습니다.

ie7 + 및 기타 브라우저 ( http://caniuse.com/minmaxwh )에서 지원됩니다 .


가능한 모든 비율의 이미지에서 작동합니다.

$(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
        }
    });
});

$('#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
});

이미지가 비례하면이 코드는 래퍼를 이미지로 채 웁니다. 이미지가 비례하지 않으면 추가 너비 / 높이가 잘립니다.

    <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>

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"/>


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);
      }
  }

Have a look at this piece...

/**
 * @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
    };
}

2 Steps:

Step 1) calculate the ratio of the original width / original height of Image.

2 단계) 새 높이에 해당하는 새 너비를 얻으려면 original_width / original_height 비율에 원하는 새 높이를 곱하십시오.


이것은 드래그 할 수있는 항목에 대해 완전히 효과가 있습니다-aspectRatio : true

.appendTo(divwrapper).resizable({
    aspectRatio: true,
    handles: 'se',
    stop: resizestop 
})

참고 URL : https://stackoverflow.com/questions/3971841/how-to-resize-images-proportionally-keeping-the-aspect-ratio

반응형