获得宽度&具有文件读取器的图像的高度 [英] Getting width & height of an image with filereader
问题描述
我正在构建一个图像调整大小/裁剪,并且我想在一个模态(引导)编辑它之后显示一个实时预览。这个应该工作,我相信,但我只是在console.log中得到0。这需要将原始图像的宽度和高度加载到另一个脚本中(我将在之后执行,只需要在console.log /一个变量中)
I am building an image resize/crop, and I'd like to show a live preview after they've edited it in a modal (bootstrap). This should work, I believe, but I just get 0 in console.log. This requires feeding the width and the height of the original image into another script (which I'll do after, just need them in console.log/a variable for now)
function doProfilePictureChangeEdit(e) {
var files = document.getElementById('fileupload').files[0];
var reader = new FileReader();
reader.onload = (function(theFile) {
document.getElementById('imgresizepreview').src = theFile.target.result;
document.getElementById('profilepicturepreview').src = theFile.target.result;
}
);
reader.readAsDataURL(files);
var imagepreview = document.getElementById('imgresizepreview');
console.log(imagepreview.offsetWidth);
$('img#imgresizepreview').imgAreaSelect({
handles: true,
enable: true,
aspectRatio: "1:1",
onSelectEnd: preview
});
$('#resizeprofilepicturemodal').modal('show');
};
推荐答案
您必须等待图像加载。尝试处理 .onload
中的元素。
You have to wait for the image to load. Try handling the element inside .onload
.
我也简化了设置二者的来源的过程元素你应该怎么做(用jQuery)。
I've also simplified the process of setting the source of the two elements to how you should be doing it (with jQuery).
reader.onload = (function(theFile) {
var image = new Image();
image.src = theFile.target.result;
image.onload = function() {
// access image size here
console.log(this.width);
$('#imgresizepreview, #profilepicturepreview').attr('src', this.src);
};
});
这篇关于获得宽度&具有文件读取器的图像的高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!