javascript - 同步检索图像分辨率
问题描述
我需要一个函数,它需要URL
一些argument
,image
并且是同步的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;
}
解决方案
编辑我完全想念这个。您可以通过简单地将代码移动到内部来完成,$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
。将您的函数更新为async
return Promise
,resolve
它何时img
为loaded
。
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>
或者,您可以使用Promise
withthen
和resolve
它 fromonload
之后callback
将从 调用函数then
。synchronous
所以它的工作方式与代码类似。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>
推荐阅读
- java - 如何在Java中创建几个整数和输入整数的“最佳拟合”比较?
- mysql - 根据日期选择最后插入的行
- java - Java如何从浏览器/系统自动请求用户PKI证书?
- google-cloud-platform - 如何禁用 gke 主机的自动升级(不仅仅是节点池)
- r - 在 R 中通过 ID 随机分配已建立的值
- ruby-on-rails - 没有路线匹配 [POST] "/webhooks/orders/fulfilled" Shopify rails
- c++ - 合并排序 C++ 错误排序
- python - 在 python 脚本中有一个 wget 命令(Windows)
- python - 如何绘制时间序列的倒数
- python - 如何比 iterrows() 更有效地根据条件从 df 中删除行?(Python)