前端js获取图片大小 扩展名_前端 JS 获取 Image 图像 宽高 尺寸

前端 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

fd1b92d74fb33c82998056d8d5719e2b.png

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

dc03d479f0c763346a9eb46c40e5ea7f.png

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

b5e255912aa6cedf74b323cccd08accb.png

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

01c220b016ed00a6b9cd3c4c92e1ee58.png

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

内容来源于网络如有侵权请私信删除

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值