首页 > 解决方案 > 获取图像尺寸并将它们应用于另一个图像

问题描述

问题:我有 2 张图像,一张是从我的数据库中使用src=data:image;base64,$row[2]并给出尺寸的。

另一张图片取自 HTML 元素,ID=img00它是透明图片。我需要透明图像与从我的数据库中获取的图像具有相同的宽度和高度。

我的猜测:我想将 getMeta 输出保存到宽度和高度的 2 个变量中,稍后我将使用它来代替'200px'.

你相信有比这段代码更聪明的方法吗?否则,我必须做些什么来保存 getMeta 输出并使用它而不是 200px?

  function getMeta(url, callback) {
    var img = new Image();
    img.src = url;
    img.onload = function() { callback(this.width, this.height); }
}

getMeta(
  "data:image;base64,$row[2]",
  function(width, height) { alert(width + 'px ' + height + 'px') }
);

var img00 = document.getElementById('img00');
if(img00 && img00.style) {
    img00.style.height = '200px';
    img00.style.width = '200px';
}

标签: javascript

解决方案


如果您想使用 getMeta 内部的值,您将不得不更改最后一个代码块的执行时间。也许是这样的?

function getMeta(url, callback) {
    var img = new Image();
    img.src = url;
    img.onload = function() { callback(this.width, this.height); }
}

function sizeImg00(w,h){
    var img00 = document.getElementById('img00');
    if(img00 && img00.style) {
        img00.style.height = h + 'px';
        img00.style.width = w + 'px';
    }
}

getMeta(
    "data:image;base64,$row[2]",
    function(width, height) { 
        console.log(width + 'px ' + height + 'px');
        sizeImg00(width, height);
    }
);

推荐阅读