日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > HTML >内容正文

HTML

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

發布時間:2023/12/10 HTML 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 前端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

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

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

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

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

總結

以上是生活随笔為你收集整理的前端js获取图片大小 扩展名_前端 JS 获取 Image 图像 宽高 尺寸的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。