当前位置: 移动技术网 > IT编程>网页制作>CSS > 前端 JS 获取 Image 图像 宽高 尺寸

前端 JS 获取 Image 图像 宽高 尺寸

2019年11月02日  | 移动技术网IT编程  | 我要评论

邯郸市25中,win7 精简版,石家庄搜房网租房

前端 js 获取 image 图像 宽高 尺寸

简介

项目中用到获取图片的原始尺寸,然后适配宽高;网上的大部分前端解决方案,都是new image()后,在onload事件中获取image的尺寸。
在图片数量较多的时候,这样的获取效率实在是低下。所有就有了这篇文章。通过直接读取解析文件的字节码来获取图片的尺寸。

image_head_sigs

var image_head_sigs = {
    gif: [0x47, 0x49, 0x46], //'g' 'i' 'f' ascii
    png: [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a],
    jpg: [0xff, 0xd8, 0xff, 0xe0],
    bmp: [0x42, 0x4d]
}

png

file

function readpng(bytes) {
    if (bytes.slice(0, 8).tostring() === image_head_sigs.png.tostring()) {
        let width = readuint32be(bytes, 16);
        let height = readuint32be(bytes, 20);
        return { width, height }
    }
}

jpg

file

function readjpg(bytes) {
    if (bytes.slice(0, 4).tostring() === image_head_sigs.jpg.tostring()) { 
        const m_sof0 = 0xc0; /* start of frame n */
        const m_sof1 = 0xc1; /* n indicates which compression process */
        const m_sof2 = 0xc2; /* only sof0-sof2 are now in common use */
        const m_sof3 = 0xc3;
        const m_sof5 = 0xc5; /* nb: codes c4 and cc are not sof markers */
        const m_sof6 = 0xc6;
        const m_sof7 = 0xc7;
        const m_sof9 = 0xc9;
        const m_sof10 = 0xca;
        const m_sof11 = 0xcb;
        const m_sof13 = 0xcd;
        const m_sof14 = 0xce;
        const m_sof15 = 0xcf;
        for (let i = 0; i < bytes.length; i++) {
            if (bytes[i] === 0xff) {
                switch (bytes[i + 1]) {
                    case m_sof0:
                    case m_sof1:
                    case m_sof2:
                    case m_sof3:
                    case m_sof5:
                    case m_sof6:
                    case m_sof7:
                    case m_sof9:
                    case m_sof10:
                    case m_sof11:
                    case m_sof13:
                    case m_sof14:
                    case m_sof15:
                        {
                            //高在前,宽在后。
                            let width = readuint16be(bytes, i + 7)
                            let height = readuint16be(bytes, i + 5)
                            return { width, height }
                        }
                    default:
                        break;
                }
            }
        }
    }
}

gif

file

function readgif(bytes) {
    if (bytes.slice(0, 3).tostring() === image_head_sigs.gif.tostring()) {
        let width = readuint16le(bytes, 6);
        let height = readuint16le(bytes, 8);
        return { width, height }
    }
}

bmp

file

function readbmp(bytes) {
    if (bytes.slice(0, 2).tostring() === image_head_sigs.bmp.tostring()) {
        //虽然格式为4字节,这里只取2字节,确保height为正数。为负数时,图像为倒置图像。
        let height = readuint16le(bytes, 22);
        let width = readuint16le(bytes, 18);
        return { width, height }
    }
}

npm

npm i image-dimensionj

npm地址

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网