获取真实的图片尺寸javascript

时间:2016-10-20 12:19:11

标签: javascript jquery html image file-upload

好的,我在这里有这个功能:

function realImgDimension(img) {
    var i = new Image();
    i.src = img.src;
    return {
        naturalWidth: i.width,
        naturalHeight: i.height
    };
}

var myImage = document.getElementById('blah');
myImage.addEventListener('load', function() {
    var realSize = realImgDimension(this);
    console.log('My width is: ', realSize.naturalWidth);
    console.log('My height is: ', realSize.naturalHeight);
});

当我上传例如1530x2500的图像时,它打印宽度为2500,高度为1530.为什么会发生这种情况?如果我有一个2500x1300的图像,它会打印出来。因此,图像的宽度小于它们的高度,或图像的高度"

有什么想法吗?

这就是我所说的onchange

function readURL(files) {
    if (files && files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {
            $('#blah')
                    .attr('src', e.target.result)
                    .width($(window).width() * 0.3)
        };
        reader.readAsDataURL(files[0]);
    }

}

这是我的表格

    <div class="form-group">
        {{ Form::label('image', 'Slider Image') }}<br>
        <img id="blah" alt="your image" style="background-color:black; margin-top:10px; border-radius:5px; image-orientation: from-image;"/><br><br>
        <div style="position:relative;">
            <a class='btn btn-primary' href='javascript:;'>
                Choose File...
                <input type="file" style='position:absolute;z-index:2;top:0;left:0;filter: alpha(opacity=0);-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";opacity:0;background-color:transparent;color:transparent;' name="image" id="image" size="40"  accept="image/gif, image/jpeg, image/png" onchange="readURL(this.files);">
            </a>
            &nbsp;
            <span class='label label-info' id="upload-file-info"></span>
        </div>
    </div>

1 个答案:

答案 0 :(得分:0)

You should use/set images to dimensions with a power of two (i.e. 2500, 1600). You should also check orientations whether printing a portrait on a landscape and vice versa. Maybe this documentation may help you: WebGL and the power of two image size