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下来,但是已经先有占位符,然后一点一点的加载。既然有占位符那应该是请求图片资源服务器响应后返回了宽和高。可服务器什么时候响应并返回宽高的数据没有触发事件,所以只能用轮询的方法。这个方法应该会比第一种方法能更早的取得图片的宽和高。

  • 相关阅读:
    tomcat7修改tomcat-users.xml文件,但服务器重启后又自动还原了。
    show命令
    Hive 桶表
    Hive是读时模式
    Hive命令 参数
    Hive设置变量
    hive 排序 order by sort by distribute by cluster by
    Hive常用配置
    hive 排序 order by sort by distribute by cluster by
    配置hive使用mysql存储metadata metadatastore
  • 原文地址:https://www.cnblogs.com/wxb1314/p/13288199.html
Copyright © 2011-2022 走看看