UNPKG

@khoohaoyit/image-size

Version:

A stream based image size extractor in Node

78 lines (75 loc) 3.07 kB
"use strict"; var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var g = generator.apply(thisArg, _arguments || []), i, q = []; return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; Object.defineProperty(exports, "__esModule", { value: true }); exports.extractPnmSize = void 0; exports.extractPnmSize = function (stream) { return __asyncGenerator(this, arguments, function* () { const signature = yield __await(stream.readString(0, 2)); if (PNMTypes[signature] === undefined) return yield __await(void 0); let width, height; loop: for (let offset = 3; width === undefined || height === undefined; ++offset) { const lineBuffers = []; for (; true; ++offset) { const buf = yield __await(stream.read(offset, 1)); if (buf.indexOf('\n') === 0) break; lineBuffers.push(buf); } const line = Buffer.concat(lineBuffers) + ''; if (line.startsWith('#')) // comment continue; if (signature !== 'P7') { // pam [width, height] = line .split(' ') .map(val => +val); break; } const [type, value] = line.split(' '); switch (type) { default: break; case 'ENDHDR': break loop; case 'WIDTH': { width = +value; } break; case 'HEIGHT': { height = +value; } break; } } if (width === undefined || height === undefined) return yield __await(void 0); return yield __await(yield yield __await({ width, height })); }); }; const PNMTypes = { P1: 'pbm/ascii', P2: 'pgm/ascii', P3: 'ppm/ascii', P4: 'pbm', P5: 'pgm', P6: 'ppm', P7: 'pam', PF: 'pfm', }; /* ppm file format specification -> https://netpbm.sourceforge.net/doc/ppm.html */