zoukankan      html  css  js  c++  java
  • JS快速获取图片宽高

    方法一:

    function getImgInfo (url) {
                return new Promise((resolve, reject) => {
                    let img = new Image();
                    img.src = url;
                    img.onload = function () {
                        resolve({
                             img.width,
                            height: img.height
                        });
                    };
                    img.onerror = function () {
                        reject(new Error("图片加载错误!"));
                    }

                });
            }
            
            getImgInfo('http://b.zol-img.com.cn/desk/bizhi/image/2/2560x1600/.jpg').then(imgInfo => {
                console.log(imgInfo);
            }).catch(error => {
                console.log(error);
            });
     

    方法二:

    function getImgInfo (url) {
                return new Promise((resolve, reject) => {
                    let img = new Image();
                    img.src = url;
                    let timer = setInterval(function () {
                        if (img.width > 0 || img.height > 0) {
                            resolve({
                                 img.width,
                                height: img.height
                            })
                            clearInterval(timer);
                        }
                    }, 50);
                });
            }
            
            getImgInfo('http://b.zol-img.com.cn/desk/bizhi/image/2/2560x1600/1365477614755.jpg').then(imgInfo => {
                console.log(imgInfo);
            });

    注: 我们常常知道有些图片虽然没有完全download下来,但是已经先有占位符,然后一点一点的加载。既然有占位符那应该是请求图片资源服务器响应后返回了宽和高。可服务器什么时候响应并返回宽高的数据没有触发事件,所以只能用轮询的方法。这个方法应该会比第一种方法能更早的取得图片的宽和高。

  • 相关阅读:
    重定向URL
    【有意思的BUG】分享按钮 分享功能
    【有意思的BUG】浏览器的Title和Icon
    【有意思的BUG】需要停止的进程
    【NO.8】jmeter-场景-上传文件-send-a-file
    nmon-监控测试服务器
    SecureCRT-转换密钥-Xshell-配置服务-使用xshell登录远程linux服务器
    <转>【读fastclick源码有感】彻底解决tap“点透”,提升移动端点击响应速度
    javascript判断鼠标按键和键盘按键的方法
    javascript 中几种实用的跨域方法原理详解(转)
  • 原文地址:https://www.cnblogs.com/wxb1314/p/13288199.html
Copyright © 2011-2022 走看看