首页 > 解决方案 > 同步检索图像分辨率

问题描述

我需要一个函数,它需要URL一些argumentimage并且是同步的returns the resolution。我希望该功能在检索图像时简单地挂起。

沿着这些思路:

function getImageDimensions(imageData) {
    $("body").append("<img id='hiddenImage' src='" + imageData />"');

    /* Wait until image is loaded */

    var width = $('#hiddenImage').width();
    var height = $('#hiddenImage').height();
    $('#hiddenImage').remove();
    return width;
}

标签: javascriptjquery

解决方案


编辑我完全想念这个。您可以通过简单地将代码移动到内部来完成,$img.on('load', function() {...}如下所示。

function getImageDimensions(imageData) {
  var $img = $(`<img id='hiddenImage' src='${imageData}' />`);
  
  $img.on('load', function() {
    /* Wait until image is loaded */
    var width = $('#hiddenImage').width();
    var height = $('#hiddenImage').height();
    $('#hiddenImage').remove();
    alert('width = ' + width);
    console.log(width);
  });
  
  $("body").append($img);
}

getImageDimensions(`https://i.stack.imgur.com/L6RvS.png?s=48&g=1`);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>


或者 ,与其尝试使其同步,不如尝试使其同步async。将您的函数更新为asyncreturn Promiseresolve它何时imgloaded

getImageDimensions从另一个async函数调用并await getImageDimensions在下面使用我已经用test.

async function getImageDimensions(imageData) {
  return new Promise((resolve) => {
    var $img = $(`<img id='hiddenImage' src='${imageData}' />`);
    $img.on('load', function() {
    /* Wait until image is loaded */      
      var width = $('#hiddenImage').width();
      var height = $('#hiddenImage').height();
      $('#hiddenImage').remove();
      alert('width = ' + width);
      resolve(width);
    });

    $("body").append($img);
  });
}

async function test() {
  let a = await getImageDimensions(`https://i.stack.imgur.com/L6RvS.png?s=48&g=1`);
  console.log(a);
}

test();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>


或者,您可以使用Promisewiththenresolve它 fromonload之后callback将从 调用函数thensynchronous所以它的工作方式与代码类似。img您可以编写在内部加载后应该完成的代码then

function getImageDimensions(imageData) {
  new Promise((resolve) => {
    var $img = $(`<img id='hiddenImage' src='${imageData}' />`);
    $img.on('load', function() {
      resolve($img);
    });
    $("body").append($img);

  }).then((result) => {
    /* Wait until image is loaded */
    var width = $('#hiddenImage').width();
    var height = $('#hiddenImage').height();
    $('#hiddenImage').remove();
    alert('width = ' + width);
    console.log(width);
  });
}

getImageDimensions(`https://i.stack.imgur.com/L6RvS.png?s=48&g=1`);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>


推荐阅读