node.js解决获取图片真实文件类型的问题(2)

function readBits(buffer, offset, bitOffset, bitLen, signed) {
    var val = 0;
   
    var neg = false;
    if (signed) {
        if (readBit(buffer, offset, bitOffset) > 0) {
            neg = true;
        }
        bitLen--;
        bitOffset++;
    }

var bytes = [];
    for (var i = 0; i < bitLen; i++) {
        var b = readBit(buffer, offset, bitOffset + i);
        if (i>0 && (bitLen - i) % 8 == 0) {
            bytes.push(val);
            val = 0;
        }
        val <<= 1;
        val |= b;
    }
    bytes.push(val);

val = new Buffer(bytes);
    val.negative = neg?true:false;
    return val;
}

function imageInfoPng(buffer) {
    var imageHeader = [0x49, 0x48, 0x44, 0x52],
        pos = 12;

if (!checkSig(buffer, pos, imageHeader)) {
        return false;
    }

pos += 4;
    return {
        type: 'image',
        format: 'PNG',
        mimeType: 'image/png',
        width: readUInt32(buffer, pos, true),
        height: readUInt32(buffer, pos+4, true),
    };
}

function imageInfoJpg(buffer) {
    var pos = 2,
        len = buffer.length,
        sizeSig = [0xff, [0xc0, 0xc2]];

while (pos < len) {
        if (checkSig(buffer, pos, sizeSig)) {
            pos += 5;
            return {
                type: 'image',
                format: 'JPG',
                mimeType: 'image/jpeg',
                width: readUInt16(buffer, pos+2, true),
                height: readUInt16(buffer, pos, true),
            };
        }

pos += 2;
        var size = readUInt16(buffer, pos, true);
        pos += size;
    }
}

function imageInfoGif(buffer) {
    var pos = 6;

return {
        type: 'image',
        format: 'GIF',
        mimeType: 'image/gif',
        width: readUInt16(buffer, pos, false),
        height: readUInt16(buffer, pos+2, false),
    };
}

function imageInfoSwf(buffer) {
    var pos = 8,
        bitPos = 0,
        val;

if (buffer[0] === 0x43) {
        try {
            // If you have zlib available ( npm install zlib ) then we can read compressed flash files
            buffer = require('zlib').inflate(buffer.slice(8, 100));
            pos = 0;
        }
        catch (ex) {
            // Can't get width/height of compressed flash files... yet (need zlib)
            return {
                type: 'flash',
                format: 'SWF',
                mimeType: 'application/x-shockwave-flash',
                width: null,
                height: null,
            }
        }
    }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wgxxyp.html