UNPKG

node-merge-images

Version:

Merges images. You can optionally set the merging orientation (vertical or horizontal), margins between images, etc.

2 lines (1 loc) 8.54 kB
import t from"fs";import e from"path";import r from"child_process";import i from"events";var n,o,s=(n=function(t,e){var n=i.EventEmitter;function o(t,e){var i={encoding:"utf8",timeout:0,maxBuffer:512e3,killSignal:"SIGKILL",output:null},o=arguments[arguments.length-1];if("function"!=typeof o&&(o=null),"object"==typeof arguments[2])for(var s=Object.keys(i),a=0;a<s.length;a++){var u=s[a];void 0!==arguments[2][u]&&(i[u]=arguments[2][u])}var h=r.spawn(t,e),c=!1,p=!1,f=function(t){this.proc=t,this.stderr=new m,t.emitter=new n,t.on=t.emitter.on.bind(t.emitter),this.out=t.emitter.emit.bind(t.emitter,"data"),this.err=this.stderr.out.bind(this.stderr),this.errCurrent=this.stderr.current.bind(this.stderr)};f.prototype.finish=function(t){this.proc.emitter.emit("end",t,this.errCurrent())};var m=function(t){this.stdout={contents:""},this.stderr={contents:""},this.callback=t;var e=function(t){return function(e){t.contents+=e,!c&&t.contents.length>i.maxBuffer&&(h.kill(i.killSignal),c=!0)}};this.out=e(this.stdout),this.err=e(this.stderr)};m.prototype.current=function(){return this.stdout.contents},m.prototype.errCurrent=function(){return this.stderr.contents},m.prototype.finish=function(t){this.callback(t,this.stdout.contents,this.stderr.contents)};var d,l=o?new m(o):new f(h);i.timeout>0&&(d=setTimeout((function(){c||(h.kill(i.killSignal),p=!0,c=!0,d=null)}),i.timeout)),h.stdout.setEncoding(i.encoding),h.stderr.setEncoding(i.encoding),h.stdout.addListener("data",(function(t){l.out(t,i.encoding)})),h.stderr.addListener("data",(function(t){l.err(t,i.encoding)}));var g=process.versions.node.split(".");return h.addListener(0==g[0]&&g[1]<7?"exit":"close",(function(t,e){if(d&&clearTimeout(d),0===t&&null===e)l.finish(null);else{var r=new Error("Command "+(p?"timed out":"failed")+": "+l.errCurrent());r.timedOut=p,r.killed=c,r.code=t,r.signal=e,l.finish(r)}})),h}function s(t){return t=t.split(/ /),new Date(t[0].replace(/:/g,"-")+" "+t[1]+" +0000")}function a(t){return t.replace(a.RE,(function(t){return 1===t.length?t.toLowerCase():t.substr(0,t.length-1).toLowerCase()+t.substr(t.length-1)}))}e.identify=function(t,r){var i,n=Array.isArray(t),s=n?[].concat(t):["-verbose",t];if("object"==typeof s[s.length-1]){if(i=!0,t=s[s.length-1],s[s.length-1]="-",!t.data)throw new Error('first argument is missing the "data" member')}else"function"==typeof t&&(s[s.length-1]="-",r=t);var a=o(e.identify.path,s,{timeout:12e4},(function(t,e,i){var o,s;t||(n?o=e:(s=(o=function(t){var e,r,i,n,o=t.split("\n"),s={},a=[s],u=0,h=[i];for(n in o.shift(),o)if((i=(e=o[n]).search(/\S/))>=0){for(r=e.split(": "),i>u&&h.push(i);i<u&&a.length;)h.pop(),s=a.pop(),u=h[h.length-1];r.length<2?(a.push(s),s=s[e.split(":")[0].trim().toLowerCase()]={}):s[r[0].trim().toLowerCase()]=r[1].trim(),u=i}return s}(e)).geometry.split(/x/),o.format=o.format.match(/\S*/)[0],o.width=parseInt(s[0]),o.height=parseInt(s[1]),o.depth=parseInt(o.depth),void 0!==o.quality&&(o.quality=parseInt(o.quality)/100))),r(t,o)}));return i&&("string"==typeof t.data?(a.stdin.setEncoding("binary"),a.stdin.write(t.data,"binary"),a.stdin.end()):a.stdin.end(t.data)),a},e.identify.path="identify",a.RE=/^[A-Z]+/;var u={bitsPerSample:Number,compression:Number,exifImageLength:Number,exifImageWidth:Number,exifOffset:Number,exposureProgram:Number,flash:Number,imageLength:Number,imageWidth:Number,isoSpeedRatings:Number,jpegInterchangeFormat:Number,jpegInterchangeFormatLength:Number,lightSource:Number,meteringMode:Number,orientation:Number,photometricInterpretation:Number,planarConfiguration:Number,resolutionUnit:Number,rowsPerStrip:Number,samplesPerPixel:Number,sensingMethod:Number,stripByteCounts:Number,subSecTime:Number,subSecTimeDigitized:Number,subSecTimeOriginal:Number,customRendered:Number,exposureMode:Number,focalLengthIn35mmFilm:Number,gainControl:Number,saturation:Number,sharpness:Number,subjectDistanceRange:Number,subSecTime:Number,subSecTimeDigitized:Number,subSecTimeOriginal:Number,whiteBalance:Number,sceneCaptureType:Number,dateTime:s,dateTimeDigitized:s,dateTimeOriginal:s};e.readMetadata=function(t,r){return e.identify(["-format","%[EXIF:*]",t],(function(t,e){var i={};t||e.split(/\n/).forEach((function(t){var e=t.indexOf("=");if(-1!==e){var r=t.substr(0,e).replace("/","-"),n=t.substr(e+1).trim(),o="default",s=r.indexOf(":");if(-1!==s&&(o=r.substr(0,s),r=r.substr(s+1),"exif"===o)){r=a(r);var h=u[r];h&&(n=h(n))}o in i?i[o][r]=n:i[o]={key:n}}})),r(t,i)}))},e.convert=function(t,r,i){var n={encoding:"binary"};return"function"==typeof r?(i=r,r=0):"number"!=typeof r&&(r=0),r&&(r=parseInt(r))>0&&!isNaN(r)&&(n.timeout=r),o(e.convert.path,t,n,i)},e.convert.path="convert";var h=function(t,r){var i=e.convert(t.args,t.opt.timeout,r);return t.opt.srcPath.match(/-$/)&&("string"==typeof t.opt.srcData?(i.stdin.setEncoding("binary"),i.stdin.write(t.opt.srcData,"binary"),i.stdin.end()):i.stdin.end(t.opt.srcData)),i};e.resize=function(t,r){var i=e.resizeArgs(t);return h(i,r)},e.crop=function(t,r){if("object"!=typeof t)throw new TypeError("First argument must be an object");if(!t.srcPath&&!t.srcData)throw new TypeError("No srcPath or data defined");if(!t.height&&!t.width)throw new TypeError("No width or height defined");if(t.srcPath)var i=t.srcPath;else i={data:t.srcData};e.identify(i,(function(i,n){if(i)return r&&r(i);var o=e.resizeArgs(t),s=!1,a=!1,u=[];o.args.forEach((function(e){if(!0===a&&(console.log("arg",e),a=!1),s||"-resize"==e||u.push(e),"-resize"==e&&(console.log("resize arg"),s=!0,a=!0),"-crop"===e&&(console.log("crop arg"),a=!0),"-resize"!=e&&s){var r=n.width/n.height<o.opt.width/o.opt.height?o.opt.width+"x":"x"+o.opt.height,i=t.gravity?t.gravity:"Center";u=u.concat(["-resize",r,"-gravity",i,"-crop",o.opt.width+"x"+o.opt.height+"+0+0","+repage"]),s=!1}})),o.args=u,h(o,r)}))},e.resizeArgs=function(t){var e={srcPath:null,srcData:null,srcFormat:null,dstPath:null,quality:.8,format:"jpg",progressive:!1,colorspace:null,width:0,height:0,strip:!0,filter:"Lagrange",sharpening:.2,customArgs:[],timeout:0};if("object"!=typeof t)throw new Error("first argument must be an object");for(var r in e)r in t&&(e[r]=t[r]);if(!e.srcPath&&!e.srcData)throw new Error("both srcPath and srcData are empty");if(e.format||(e.format="jpg"),e.srcPath||(e.srcPath=e.srcFormat?e.srcFormat+":-":"-"),e.dstPath||(e.dstPath=e.format?e.format+":-":"-"),0===e.width&&0===e.height)throw new Error("both width and height can not be 0 (zero)");var i=[e.srcPath];e.sharpening>0&&(i=i.concat(["-set","option:filter:blur",String(1-e.sharpening)])),e.filter&&(i.push("-filter"),i.push(e.filter)),e.strip&&i.push("-strip"),(e.width||e.height)&&(i.push("-resize"),0===e.height?i.push(String(e.width)):0===e.width?i.push("x"+String(e.height)):i.push(String(e.width)+"x"+String(e.height))),e.format=e.format.toLowerCase();var n="jpg"===e.format||"jpeg"===e.format;return n&&e.progressive&&(i.push("-interlace"),i.push("plane")),n||"png"===e.format?(i.push("-quality"),i.push(Math.round(100*e.quality).toString())):"miff"!==e.format&&"mif"!==e.format||(i.push("-quality"),i.push(Math.round(9*e.quality).toString())),e.colorspace&&(i.push("-colorspace"),i.push(e.colorspace)),Array.isArray(e.customArgs)&&e.customArgs.length&&(i=i.concat(e.customArgs)),i.push(e.dstPath),{opt:e,args:i}}},n(o={exports:{}},o.exports),o.exports);s.identify,s.readMetadata,s.convert,s.resize,s.crop,s.resizeArgs;const a=require("fs-extra");var u=async(r,i,n={})=>new Promise(((o,u)=>{try{n=Object.assign({direction:"vertical",background:"white",offset:0},n),function(e,r,i){if(!Array.isArray(e))throw new TypeError("inputPaths must be an array that contains images");if(e.length<1)throw new TypeError("At least inputPaths must contain more than one image");if(!r)throw new TypeError("outputPath should be a file path");if(!/^(vertical|horizontal)$/.test(i.direction))throw new TypeError('The direction option should be "vertical" or "horizontal"');if(i.offset<0)throw new TypeError("The offset option should be a number greater than or equal to 0");const n=e.filter((e=>!t.existsSync(e)));if(n.length>0)throw new TypeError(`Input path ${n.join(", ")} not found`)}(r,i,n);const h=[];h.push("-background"),h.push(n.background),h.push("-size"),h.push("vertical"===n.direction?`x${n.offset}`:`${n.offset}x`),h.push(r[0]);for(let t of r.slice(1))n.offset>0&&h.push("xc:none"),h.push(t);h.push("vertical"===n.direction?"-append":"+append"),h.push(i),t.existsSync(e.dirname(i))||(a.mkdirsSync(e.dirname(i)),t.chmodSync(e.dirname(i),493)),s.convert(h,(t=>{t?u(t):o()}))}catch(t){u(t)}}));export{u as default};