无法获取尺寸-高度和宽度:结果总是“未定义”。我显然不明白JavaScript在这里是如何工作的。但是,我能够显示该文件。
PHP文件包含以下输入标记,用于选择多张图片:
$output = "<input class=\"wpisNazwyWkladow\"
id=\"wpis_tabela_zdjecie_wybieracz\" type=\"file\" multiple
name=\"ads_photofile\">";这就是有问题的JavaScript脚本:
var input = $(this); // works
var ilosc = input[0].files.length;
var pliki = input[0].files;
for (var i = 0; i < ilosc; i++)
{
var tmppath = URL.createObjectURL(pliki[i]); // works - displays
var nazwa = pliki[i].name; // works
var tempRozmiar = pliki[i].size; // works
var typ = pliki[i].type; // typ fotki // works
// The part that does not work:
tempWysokosc = tmppath.height;
tempSzerokosc = tmppath.width;
}我希望"tempWysokosc“和"tempSzerokosc”是一个整数值。
我需要帮助。
发布于 2019-05-28 11:29:19
在您的代码中,tmppath是URL.createObjectURL()的结果,即一个字符串。
这个字符串显然既没有width也没有height。您需要的是从加载的<img>元素中检索这些值,该元素的src将被设置为tmppath。但是这个过程总是异步的,所以你可能需要重构你的代码来接受这种异步性:
input.oninput = e => {
const ilosc = input.files.length;
const pliki = input.files;
for (let i = 0; i < ilosc; i++)
{
const tmppath = URL.createObjectURL(pliki[i]); // works - displays
const nazwa = pliki[i].name; // works
const tempRozmiar = pliki[i].size; // works
const typ = pliki[i].type; // typ fotki // works
const img = new Image();
// async
img.onload = e => {
const tempWysokosc = img.height;
const tempSzerokosc = img.width;
console.log({
name: nazwa,
size: tempRozmiar,
type: typ,
width: tempWysokosc,
height: tempSzerokosc
});
};
img.src = tmppath;
}
}<input id="input" type="file" accept="image/*" multiple>
请注意,如果你有很多这样的图像,你想要检索尺寸,你可能会对this Q/A感兴趣,它公开了一种直接读取文件的方法,避免了解码图像的巨大开销。
发布于 2019-05-28 11:16:07
当您向图像请求高度时,图像可能尚未完全渲染,因此请在onload事件之后设置宽度和高度:
tmppath.onload=function() {
tempWysokosc = tmppath.height;
tempSzerokosc = tmppath.width;
}https://stackoverflow.com/questions/56334495
复制相似问题