【问题标题】:Javascript Image ResizeJavascript图像调整大小
【发布时间】:2010-09-15 07:09:50
【问题描述】:

有人知道如何使用 JavaScript 按比例调整图像大小吗?

我试图通过动态添加属性heightwidth 来修改DOM,但似乎在IE6 上不起作用。

【问题讨论】:

标签: javascript internet-explorer-6 image-manipulation


【解决方案1】:

不要修改图片的height和width属性,而是尝试修改CSS的height和width。

myimg = document.getElementById('myimg');
myimg.style.height = "50px";
myimg.style.width = "50px";

一个常见的“陷阱”是高度和宽度样式是包含单位的字符串,如上例中的“px”。

编辑 - 我认为直接设置高度和宽度而不是使用 style.height 和 style.width 应该可行。它还具有已经具有原始尺寸的优点。你能发布一些你的代码吗?你确定你是在标准模式而不是怪癖模式?

这应该可行:

myimg = document.getElementById('myimg');
myimg.height = myimg.height * 2;
myimg.width = myimg.width * 2;

【讨论】:

    【解决方案2】:

    要按比例修改图像,只需更改宽度/高度 css 属性之一,将另一个设置为自动。

    image.style.width = '50%'
    image.style.height = 'auto'
    

    这将确保其纵横比保持不变。

    请记住,浏览器倾向于糟糕很好地调整图像大小 - 您可能会发现调整后的图像看起来很糟糕。

    【讨论】:

    • 可能会在上传到服务器之前添加关于调整图像大小的简介
    【解决方案3】:

    尝试了以下代码,在 WinXP Pro SP3 上的 IE6 上运行良好。

    function Resize(imgId)
    {
      var img = document.getElementById(imgId);
      var w = img.width, h = img.height;
      w /= 2; h /= 2;
      img.width = w; img.height = h;
    }
    

    在 FF3 和 Opera 9.26 中也可以。

    【讨论】:

      【解决方案4】:

      好的,解决了,这是我的最终代码

      if($(this).width() > $(this).height()) { 
       $(this).css('width',MaxPreviewDimension+'px');
       $(this).css('height','auto');
      } else {
       $(this).css('height',MaxPreviewDimension+'px');
       $(this).css('width','auto');
      }
      

      谢谢大家

      【讨论】:

      • 顺便说一句,除非您在图像上设置了高度(height 属性或通过 CSS),否则您无需显式设置 height: auto - 默认情况下已设置为
      • 不,当我调整宽度而不将高度设置为自动时,它在 IE6 中失败
      • 奇怪,我敢肯定我以前做过,并且可以正常工作。无论如何,我会相信你的话 :) 你可以在样式表中应用那个 height:auto
      • 我的理解是,在jQuery中,$()是一个类构造函数。这意味着如果您将其存储在变量中,则此代码将始终为“this”实例化四个包装器。我什至可能想将 $(this) 存储在构造函数的类级变量中。
      • var target = $(this); if (target.width() > target.height()) target.css({ "width": MaxPreviewDimension + "px", "height": "auto" }); else target.css({ "height": MaxPreviewDimension + "px", "width": auto })
      【解决方案5】:
      function resize_image(image, w, h) {
      
          if (typeof(image) != 'object') image = document.getElementById(image);
      
          if (w == null || w == undefined)
              w = (h / image.clientHeight) * image.clientWidth;
      
          if (h == null || h == undefined)
              h = (w / image.clientWidth) * image.clientHeight;
      
          image.style['height'] = h + 'px';
          image.style['width'] = w + 'px';
          return;
      }
      

      只需将 img DOM 元素或图像元素的 id 以及新的宽度和高度传递给它。

      或者您可以只传递宽度或只传递高度(如果只是高度,则将宽度传递为 null 或未定义),它会调整大小以保持纵横比

      【讨论】:

        【解决方案6】:

        使用 JQuery

        var scale=0.5;
        
        minWidth=50;
        minHeight=100;
        
        if($("#id img").width()*scale>minWidth && $("#id img").height()*scale >minHeight)
        {
            $("#id img").width($("#id img").width()*scale);
            $("#id img").height($("#id img").height()*scale);
        }
        

        【讨论】:

          【解决方案7】:

          试试这个..

          <html>
          <body>
          <head>
          <script type="text/javascript">
          function splitString()
          {
          var myDimen=document.getElementById("dimen").value;
          var splitDimen = myDimen.split("*");
          document.getElementById("myImage").width=splitDimen[0];
          document.getElementById("myImage").height=splitDimen[1];
          }
          </script>
          </head>
          
          <h2>Norwegian Mountain Trip</h2>
          <img border="0" id="myImage" src="..." alt="Pulpit rock" width="304" height="228" /><br>
          <input type="text" id="dimen" name="dimension" />
          <input type="submit" value="Submit" Onclick ="splitString()"/>
          
          </body>
          </html>
          

          在文本框中根据您的意愿给出尺寸,格式为 50*60。点击提交。您将获得调整大小的图像。用你的图片路径代替图片标签中的点。

          【讨论】:

            【解决方案8】:

            您不必使用 Javascript。您可以创建一个 CSS 类并将其应用于您的标签。

            .preview_image{
                    width: 300px;
                height: auto;
                border: 0px;
            }
            

            【讨论】:

              【解决方案9】:

              示例:如何使用百分比调整大小

              <head>
                  <script type="text/javascript">
                      var CreateNewImage = function (url, value) {
                          var img = new Image;
                          img.src = url;
                          img.width = img.width * (1 + (value / 100));
                          img.height = img.height * (1 + (value / 100));
              
                          var container = document.getElementById ("container");
                          container.appendChild (img);
                      }
                  </script>
              </head>
              <body>
                  <button onclick="CreateNewImage ('http://www.medellin.gov.co/transito/images_jq/imagen5.jpg', 40);">Zoom +40%</button>
                  <button onclick="CreateNewImage ('http://www.medellin.gov.co/transito/images_jq/imagen5.jpg', 60);">Zoom +50%</button>
                  <div id="container"></div>
              </body>
              

              【讨论】:

                【解决方案10】:

                在javascript中调整图像大小:

                $(window).load(function() {
                mitad();doble();
                });
                function mitad(){ 
                
                    imag0.width=imag0.width/2;
                    imag0.height=imag0.height/2;
                
                    }
                function doble(){ 
                  imag0.width=imag0.width*2; 
                  imag0.height=imag0.height*2;}
                

                imag0 是图像的名称:

                 <img src="xxx.jpg" name="imag0">
                

                【讨论】:

                • 谢谢,这是我可以理解和使用的代码。我发现的一件奇怪的事情是,改变宽度是我唯一需要做的事情才能缩小图像(如果我要改变高度,它实际上会使图像变平/倾斜)。
                【解决方案11】:

                我在这里有answered 这个问题:How to resize images proportionally / keeping the aspect ratio?。我在这里复制它是因为我真的认为这是一种非常可靠的方法:)

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

                【讨论】:

                  【解决方案12】:

                  这适用于所有情况。

                  function resizeImg(imgId) {
                      var img = document.getElementById(imgId);
                      var $img = $(img);
                      var maxWidth = 110;
                      var maxHeight = 100;
                      var width = img.width;
                      var height = img.height;
                      var aspectW = width / maxWidth;
                      var aspectH = height / maxHeight;
                  
                      if (aspectW > 1 || aspectH > 1) {
                          if (aspectW > aspectH) {
                              $img.width(maxWidth);
                              $img.height(height / aspectW);
                          }
                          else {
                              $img.height(maxHeight);
                              $img.width(width / aspectH);
                          }
                      }
                  }
                  

                  【讨论】:

                    【解决方案13】:

                    这是我的封面填充解决方案(类似于background-size:cover,但支持旧的IE浏览器)

                    <div class="imgContainer" style="height:100px; width:500px; overflow:hidden; background-color: black">
                        <img src="http://dev.isaacsonwebdevelopment.com/sites/development/files/views-slideshow-settings-jquery-cycle-custom-options-message.png" id="imgCat">
                    </div>
                    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.3.min.js"></script>
                    <script>
                        $(window).load(function() {
                            var heightRate =$("#imgCat").height() / $("#imgCat").parent(".imgContainer").height();
                            var widthRate = $("#imgCat").width() / $("#imgCat").parent(".imgContainer").width();
                    
                            if (window.console) {
                                console.log($("#imgCat").height());
                                console.log(heightRate);
                                console.log(widthRate);
                                console.log(heightRate > widthRate);
                            }
                            if (heightRate <= widthRate) {
                                $("#imgCat").height($("#imgCat").parent(".imgContainer").height());
                            } else {
                                $("#imgCat").width($("#imgCat").parent(".imgContainer").width());
                            }
                        });
                    </script>
                    

                    【讨论】:

                      猜你喜欢
                      • 1970-01-01
                      • 2021-06-25
                      • 2013-07-04
                      • 2021-11-07
                      • 2012-10-03
                      • 2015-01-23
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      相关资源
                      最近更新 更多