shields/lib/svg-to-img.js
Paul Melnikow 0760d17d82 Return data from svg2img via callback
Given the chunks coming from imagemagick are getting stored memory and
then tucked into a cache, this function could as easily return a buffer
via callback. Streaming is just making it more complex. (And trickier to
test!)
2017-04-12 23:13:16 +02:00

37 lines
1.1 KiB
JavaScript

var gm = require('gm');
var LruCache = require('./lru-cache.js');
var imageMagick = gm.subClass({ imageMagick: true });
// The following is an arbitrary limit (~1.5MB, 1.5kB/image).
var imgCache = new LruCache(1000);
module.exports = function (svg, format, callback) {
var cacheIndex = format + svg;
if (imgCache.has(cacheIndex)) {
// We own a cache for this svg conversion.
var result = imgCache.get(cacheIndex);
callback(result);
return;
}
var buf = Buffer.from('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' + svg);
var stream = imageMagick(buf, 'image.' + format)
.density(90)
.background(format === 'jpg' ? '#FFFFFF' : 'none')
.flatten()
.stream(format, function (err, stdout, stderr) {
if (err) { console.error(err); return; }
var chunks = [];
stdout.on('data', function(chunk) { chunks.push(chunk); });
stdout.on('finish', function() {
var result = Buffer.concat(chunks);
imgCache.set(cacheIndex, result);
callback(result);
});
});
};
// To simplify testing.
module.exports._imgCache = imgCache;