obj2gltf/lib/image.js

64 lines
1.6 KiB
JavaScript
Raw Normal View History

2015-10-16 17:32:23 -04:00
"use strict";
2016-07-22 14:09:13 -04:00
var Promise = require('bluebird');
2016-06-09 13:33:08 -04:00
var fs = require('fs-extra');
2015-10-16 17:32:23 -04:00
var path = require('path');
2016-07-22 14:09:13 -04:00
var fsReadFile = Promise.promisify(fs.readFile);
2016-06-09 13:33:08 -04:00
module.exports = loadImage;
2015-10-16 17:32:23 -04:00
function getChannels(colorType) {
switch (colorType) {
case 0: // greyscale
return 1;
case 2: // RGB
return 3;
case 4: // greyscale + alpha
return 2;
case 6: // RGB + alpha
return 4;
default:
return 3;
}
}
function getUriType(extension) {
switch (extension) {
case 'png':
return 'data:image/png';
case 'jpg':
return 'data:image/jpeg';
case 'jpeg':
return 'data:image/jpeg';
case 'gif':
return 'data:image/gif';
default:
return 'data:image/' + extension;
}
}
2016-07-22 14:09:13 -04:00
function loadImage(imagePath) {
return fsReadFile(imagePath)
.then(function(data) {
var extension = path.extname(imagePath).slice(1);
var uriType = getUriType(extension);
var uri = uriType + ';base64,' + data.toString('base64');
var info = {
transparent: false,
channels: 3,
data: data,
uri: uri
};
if (path.extname(imagePath) === 'png') {
// Color type is encoded in the 25th bit of the png
var colorType = data[25];
var channels = getChannels(colorType);
info.channels = channels;
info.transparent = (channels === 4);
}
return info;
2015-10-16 17:32:23 -04:00
});
}