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

  • 相关阅读:
    单片机控制蜂鸣器和弦音发音程序
    Ajax发送Post请求
    加壳学习笔记(一)-基础知识
    每日一小练——等值数目
    NTP配置实践
    由查找session IP 展开---函数、触发器、包
    单片机第13课:串口通信---向计算机发送数据
    [think in java]知识点学习
    【插件开发】—— 8 IPreferenceStore,插件的键/值存储!
    【插件开发】—— 7 SWT布局详解,不能再详细了!
  • 原文地址:https://www.cnblogs.com/wxb1314/p/13288199.html
Copyright © 2020-2023  润新知