├── resource ├── test.js ├── 1024.png ├── tree.png ├── wazi.png ├── happy.png ├── xueqiao.png ├── test.html ├── mustache.xmas.js ├── mustache.js └── jquery.1.7.1.min.js ├── tea.yaml ├── example └── test.js ├── utils ├── js-min.js ├── image-to-struct.js └── keep-line.js ├── .gitignore ├── CHANGELOG.md ├── package.json ├── bin └── cli ├── license.md ├── readme_en.md ├── index.汉.js ├── index.js └── readme.md /resource/test.js: -------------------------------------------------------------------------------- 1 | price_info+="价格:$"+(res[type]['perkg']/100).toFixed(2)+"/kg "; -------------------------------------------------------------------------------- /resource/1024.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/small-tou/js2image/HEAD/resource/1024.png -------------------------------------------------------------------------------- /resource/tree.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/small-tou/js2image/HEAD/resource/tree.png -------------------------------------------------------------------------------- /resource/wazi.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/small-tou/js2image/HEAD/resource/wazi.png -------------------------------------------------------------------------------- /resource/happy.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/small-tou/js2image/HEAD/resource/happy.png -------------------------------------------------------------------------------- /resource/xueqiao.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/small-tou/js2image/HEAD/resource/xueqiao.png -------------------------------------------------------------------------------- /resource/test.html: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /tea.yaml: -------------------------------------------------------------------------------- 1 | # https://tea.xyz/what-is-this-file 2 | --- 3 | version: 1.0.0 4 | codeOwners: 5 | - '0x95723d7a7a21E469F680c2634Bb929CcEae4ccDD' 6 | quorum: 1 7 | -------------------------------------------------------------------------------- /example/test.js: -------------------------------------------------------------------------------- 1 | var Js2Image = require("./../index.js"); 2 | var path = require("path"); 3 | var source = "./../resource/jquery.js"; 4 | var image = path.join(__dirname,"./../resource/happy.png"); 5 | var out = source.replace(".js",".xmas.js"); 6 | 7 | Js2Image.writeToFile(source,image,out,{ 8 | reverse:false, 9 | size:{ 10 | width:70 11 | } 12 | }).then(function(code){ 13 | 14 | }); 15 | 16 | -------------------------------------------------------------------------------- /utils/js-min.js: -------------------------------------------------------------------------------- 1 | 2 | var UglifyJS = require("uglify-js"); 3 | var fs = require("fs"); 4 | var Promise = require("bluebird"); 5 | module.exports = function(source,callback){ 6 | return new Promise(function(resolve,reject){ 7 | try{ 8 | var ast = UglifyJS.parse(source); 9 | ast.figure_out_scope(); 10 | ast.compute_char_frequency(); 11 | ast.mangle_names(); 12 | var code = ast.print_to_string(); 13 | resolve(code); 14 | }catch(e){ 15 | console.log('js minify error:',e); 16 | reject(e); 17 | } 18 | }) 19 | }; -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | 5 | # Runtime data 6 | pids 7 | *.pid 8 | *.seed 9 | 10 | # Directory for instrumented libs generated by jscoverage/JSCover 11 | lib-cov 12 | 13 | # Coverage directory used by tools like istanbul 14 | coverage 15 | 16 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 17 | .grunt 18 | 19 | # node-waf configuration 20 | .lock-wscript 21 | 22 | # Compiled binary addons (http://nodejs.org/api/addons.html) 23 | build/Release 24 | 25 | # Dependency directory 26 | # https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git 27 | node_modules 28 | 29 | bower_components 30 | 31 | config/!default.js 32 | 33 | .idea -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## 版本变更记录 2 | 3 | 4 | ## [v1.1.0](http://git.souche.com///github.com/xinyu198736/js2image/compare/v1.0.0...v1.1.0) 5 | 6 | 2018-04-03 7 | * fix: 判断正则的一个问题修复 [a4151b5](http://git.souche.com///github.com/xinyu198736/js2image/commit/a4151b5) (sunxinyu@souche.com) 8 | * docs: add some docs about options [822f663](http://git.souche.com///github.com/xinyu198736/js2image/commit/822f663) (sunxinyu@souche.com) 9 | 10 | 11 | ## v1.0.0 12 | 13 | 2015-12-27 14 | * fixed: #9 调用ImageToAscii()出错时应该使用reject(err)返回错误 [dc0c742](http://git.souche.com///github.com/xinyu198736/js2image/commit/dc0c742) (leizongmin@gmail.com) 15 | * docs: 去掉英文文档中的中文注释 [e256767](http://git.souche.com///github.com/xinyu198736/js2image/commit/e256767) (leizongmin@gmail.com) 16 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "author": { 3 | "email": "xinyu198736@gmail.com", 4 | "name": "yutou", 5 | "url": "https://github.com/xinyu198736" 6 | }, 7 | "dependencies": { 8 | "bluebird": "^3.1.1", 9 | "image-to-ascii": "^3.0.5", 10 | "minimist": "^1.2.0", 11 | "uglify-js": "^2.6.1", 12 | "underscore": "^1.8.3", 13 | "walkdo": "^0.9.6" 14 | }, 15 | "description": "用js代码和图片,生成一段可以正常运行的图形化的js源代码", 16 | "keywords": [], 17 | "license": { 18 | "type": "MIT", 19 | "url": "https://github.com/xinyu198736/image-to-js.git/blob/master/license.md" 20 | }, 21 | "name": "js2image", 22 | "optionalDependencies": {}, 23 | "repository": { 24 | "type": "git", 25 | "url": "https://github.com/xinyu198736/image-to-js.git" 26 | }, 27 | "version": "1.1.0", 28 | "bin": { 29 | "js2image": "./bin/cli" 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /bin/cli: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | 4 | var ImageToJS = require('../index.js'); 5 | var path = require('path'); 6 | var argv = require('minimist')(process.argv.slice(2)); 7 | var source = argv.s; 8 | var image = argv.i || path.join(__dirname, '../resource/tree.png'); 9 | 10 | var reverse = (argv.r === 'true' ? true : false); 11 | var fs = require('fs'); 12 | var walkdo = require('walkdo'); 13 | 14 | walkdo(source, function (file, next, context) { 15 | if(/\.xmas\.js$/.test(file) || !/\.js$/.test(file)) { 16 | next.call(context); 17 | return; 18 | } 19 | console.log('converting ' + file); 20 | var out = argv.o || file.replace('.js', '.xmas.js'); 21 | ImageToJS.writeToFile(file, image, out, { reverse: reverse }).then(function (code) { 22 | console.log('converted ' + file); 23 | next.call(context); 24 | }).catch(function (e) { 25 | next.call(context); 26 | }); 27 | }, function () { 28 | console.log('down!'); 29 | }); 30 | 31 | -------------------------------------------------------------------------------- /utils/image-to-struct.js: -------------------------------------------------------------------------------- 1 | 2 | var ImageToAscii = require("image-to-ascii"); 3 | var fs = require("fs"); 4 | var _ = require("underscore"); 5 | var Promise = require("bluebird"); 6 | var path = require("path"); 7 | /** 8 | * 将图片转换成一个可以用来处理的数组结构,用特殊字符填充结构形成字符画。 9 | * @param imagePath image path 10 | * @param options {reverse:true/false} 11 | */ 12 | module.exports = function(imagePath,options,callback){ 13 | if(!imagePath){ 14 | imagePath = path.join(__dirname , "./../resource/tree.png"); 15 | } 16 | return new Promise(function(resolve,reject){ 17 | ImageToAscii(imagePath, _.extend({colored:false,pixels:['☃',' '],reverse:false},options), function(err, converted) { 18 | if(err) return reject(err); 19 | var content = converted.replace(/\S\[0m/g,"").replace(/\n/g,"\",\n\""); 20 | var arr = []; 21 | converted.replace(/\S\[0m/g,"").split("\n").forEach(function(c){ 22 | arr.push(c); 23 | }) 24 | resolve(arr); 25 | }); 26 | }) 27 | 28 | 29 | } -------------------------------------------------------------------------------- /license.md: -------------------------------------------------------------------------------- 1 | Copyright (c) 2014 [xinyu198736], contributors 2 | 3 | Permission is hereby granted, free of charge, to any person 4 | obtaining a copy of this software and associated documentation 5 | files (the "Software"), to deal in the Software without 6 | restriction, including without limitation the rights to use, 7 | copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | copies of the Software, and to permit persons to whom the 9 | Software is furnished to do so, subject to the following 10 | conditions: 11 | 12 | The above copyright notice and this permission notice shall be 13 | included in all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 17 | OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 18 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 19 | HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 20 | WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 21 | FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 22 | OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /readme_en.md: -------------------------------------------------------------------------------- 1 | **Warning: js compressed please manual confirmation before put into production use, does not guarantee 100% operational, js and js souche.com official website of the current test have been tested, which can guarantee there is no problem after 99% compression of js 2 | 3 | # who am i? 4 | 5 | **js2image** Is a javascript source code can be compressed into a single source code ascii character painting tool, which features code compression can still run after, rather than simply makes up the final pattern. 6 | 7 | About js2image principle can see this article i writed:[Christmas, all the js code of the site compress into a Christmas tree。](http://zhuanlan.zhihu.com/yutou/20439979) 8 | 9 | # example 10 | 11 | http://f2e.souche.com/assets/js/lib/jquery-2.1.1.min.xmas.js 12 | 13 | In addition, the project has more than one resource directory is already running through the test library file. 14 | 15 | Compression effect is as follows: 16 | 17 | ![js2image Compression renderings](http://7o52oq.com2.z0.glb.qiniucdn.com/Slice%201.png) 18 | 19 | 20 | # Installation dependent system modules graphicsmagick 21 | 22 | ```bash 23 | # Ubuntu 24 | $ sudo apt-get install graphicsmagick 25 | 26 | # Fedora 27 | $ sudo dnf install GraphicsMagick 28 | 29 | # OS X 30 | $ brew install graphicsmagick 31 | 32 | # Chocolatey (package manager for Windows) 33 | # (Restart of cmd/PowerShell is required) 34 | $ choco install graphicsmagick 35 | ``` 36 | 37 | # Use the command-line tool 38 | 39 | Execute the following command to install global command: 40 | 41 | ```bash 42 | $ npm install js2image -g 43 | ``` 44 | 45 | usage: 46 | 47 | ```bash 48 | # Execute this command directly from the command line to compression, default compress a file with the extension xmas.js。 49 | # -s Source code path, necessary parameters! 50 | # -r Are inverting images, optional 51 | # -i Specifies the path of the image, default ./resource/tree.png optional 52 | 53 | $ js2image -s ./resource/jquery.js 54 | 55 | # Added support for all packaged in a folder js files, caution! Packaging does not guarantee js100% after running properly, through manual testing to confirm. 56 | $ js2image -s ./resource 57 | ``` 58 | 59 | # use in nodejs 60 | 61 | run this commands: 62 | 63 | ```bash 64 | $ npm install js2image --save 65 | ``` 66 | 67 | usage: 68 | 69 | ```javascript 70 | var Js2Image = require('js2image'); 71 | 72 | var image = './resource/tree.png'; 73 | var source = './resource/jquery.js'; 74 | var target = './target/xmas.js'; 75 | var options = {}; 76 | 77 | // get the result code 78 | var sourceCode = fs.readFileSync(source); 79 | Js2Image.getCode(sourceCode, image, options).then(function (code) { 80 | console.log(code); 81 | }) 82 | 83 | // or write into file 84 | Js2Image.writeToFile(source, image, target, options).then(function (code) { 85 | console.log(code); 86 | }); 87 | ``` 88 | -------------------------------------------------------------------------------- /index.汉.js: -------------------------------------------------------------------------------- 1 | var FS = require("fs"); 2 | 3 | var 图像结构 = require("./utils/image-to-struct.js"); 4 | 5 | var jsmin = require("./utils/js-min.js"); 6 | 7 | var 保持线 = require("./utils/keep-line.js"); 8 | 9 | var 承诺 = require("bluebird"); 10 | 11 | var JS2图像 = function(JS代码, 图像路径, 选项, 回调) { 12 | 图像结构(图像路径, 选项).then(function(结构) { 13 | jsmin(JS代码).then(function(代码) { 14 | var 保持代码 = 保持线.pickFromCode(代码); 15 | var 线 = 保持代码.replace(/([^a-zA-Z_0-9=!|&$])/g, "\n$1\n").split("\n"); 16 | 保持线.findBack(线); 17 | var 结果 = ""; 18 | while (线.length > 0) { 19 | 结构.forEach(function(S) { 20 | var 字符数组 = S.replace(/ +/g, " "); 21 | var R = S; 22 | 字符数组.split(/ +/).forEach(function(字符) { 23 | if (字符.length == 0) { 24 | return; 25 | } 26 | var 字符计数 = 字符.length; 27 | var l = pickFromLines(线, 字符计数); 28 | R = R.replace(字符, function() { 29 | return l; 30 | }); 31 | }); 32 | 结果 += R + "\n"; 33 | }); 34 | } 35 | 回调(null, 结果); 36 | }).catch(function(E) { 37 | 回调(E); 38 | }); 39 | }); 40 | }; 41 | 42 | module.exports = { 43 | writeToFile: function(js的路径, 图像路径, 输出路径, 选项) { 44 | var JS代码 = FS.readFileSync(js的路径); 45 | return new 承诺(function(决定, 拒绝) { 46 | JS2图像(JS代码.toString(), 图像路径, 选项, function(E, 代码) { 47 | 代码 = "/* generated by https://github.com/xinyu198736/js2image */ \n\n" + 代码; 48 | FS.writeFileSync(输出路径, 代码, "utf-8"); 49 | if (E) { 50 | 拒绝(E); 51 | } else { 52 | 决定(代码); 53 | } 54 | }); 55 | }); 56 | }, 57 | getCode: function(JS代码, 图像路径, 选项) { 58 | return new 承诺(function(决定, 拒绝) { 59 | JS2图像(JS代码, 图像路径, 选项, function(E, 代码) { 60 | if (E) { 61 | 拒绝(E); 62 | } else { 63 | 决定(代码); 64 | } 65 | }); 66 | }); 67 | } 68 | }; 69 | 70 | function pickFromLines(线, 计数) { 71 | var T = ""; 72 | var 已接数 = 0; 73 | var 现在的长度 = 0; 74 | for (var 我 = 0; 我 < 线.length; 我++) { 75 | var l = 线[我]; 76 | 现在的长度 += l.length; 77 | 已接数++; 78 | if (现在的长度 > 计数) { 79 | if (现在的长度 - 计数 > 3 && 已接数 > 1) { 80 | 已接数--; 81 | } 82 | break; 83 | } 84 | } 85 | for (var 我 = 0; 我 < 已接数; 我++) { 86 | var S = 线.shift(); 87 | T += S; 88 | } 89 | return T; 90 | } -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | var fs = require("fs"); 2 | var ImageToStruct = require("./utils/image-to-struct.js"); 3 | var JSMin = require("./utils/js-min.js"); 4 | var KeepLine = require("./utils/keep-line.js"); 5 | var Promise = require("bluebird"); 6 | 7 | var Js2Image = function (jsCode, imagePath, options, callback) { 8 | ImageToStruct(imagePath, options).then(function (struct) { 9 | JSMin(jsCode).then(function (code) { 10 | //fs.writeFileSync(jsPath.replace(".js",".min.js"),code,'utf-8') 11 | //提取不换行的字符串 12 | var hold_code = KeepLine.pickFromCode(code); 13 | //分离代码,以可分割单位拆分成数组。 14 | var lines = hold_code.replace(/([^a-zA-Z_0-9=!|&$])/g, "\n$1\n").split("\n"); 15 | //把分离后的代码里的占位符替换回代码。 16 | KeepLine.findBack(lines); 17 | var result = ""; 18 | while(lines.length > 0) { 19 | //循环往struct里填充代码 20 | struct.forEach(function (s) { 21 | var chars_arr = s.replace(/ +/g, " ");//一行有多组分离的***** 22 | var r = s; 23 | chars_arr.split(/ +/).forEach(function (chars) { 24 | if(chars.length == 0) { 25 | return; 26 | } 27 | var char_count = chars.length; 28 | //从lines里取出char_count数量的代码来填充,不一定精准,要确保断行正确 29 | var l = pickFromLines(lines, char_count); 30 | 31 | r = r.replace(chars, function () { 32 | return l; 33 | }) 34 | }) 35 | result += r + "\n" 36 | }) 37 | 38 | } 39 | //result就是最终的代码 40 | callback(null, result); 41 | }).catch(function (e) { 42 | callback(e); 43 | }); 44 | }) 45 | 46 | 47 | } 48 | 49 | module.exports = { 50 | /** 51 | * 从源文件读取,然后写到目标文件里。 52 | * @param jsPath 53 | * @param imagePath 54 | * @param outputPath 55 | * @param options 56 | * @param callback 57 | */ 58 | writeToFile: function (jsPath, imagePath, outputPath, options) { 59 | var jsCode = fs.readFileSync(jsPath); 60 | return new Promise(function (resolve, reject) { 61 | Js2Image(jsCode.toString(), imagePath, options, function (e, code) { 62 | 63 | code = "/* generated by https://github.com/xinyu198736/js2image */ \n\n" + code; 64 | fs.writeFileSync(outputPath, code, 'utf-8'); 65 | if(e) { 66 | reject(e); 67 | } else { 68 | resolve(code); 69 | } 70 | 71 | }) 72 | }) 73 | }, 74 | /** 75 | * 从源代码字符串开始,直接返回一个处理后的code 76 | * @param jsCode 77 | * @param imagePath 78 | * @param options 79 | * @returns {bluebird|exports|module.exports} 80 | */ 81 | getCode: function (jsCode, imagePath, options) { 82 | return new Promise(function (resolve, reject) { 83 | Js2Image(jsCode, imagePath, options, function (e, code) { 84 | if(e) { 85 | reject(e); 86 | } else { 87 | resolve(code); 88 | } 89 | }) 90 | }) 91 | 92 | } 93 | }; 94 | /** 95 | * 从lines数组里顺序取字符来填充到指定的长度,不一定精确。 96 | * @param count 97 | * @returns {string} 98 | */ 99 | function pickFromLines (lines, count) { 100 | 101 | var t = ""; 102 | var has_pick_count = 0; //取了多少次 103 | var now_length = 0; //当前填充的长度 104 | for(var i = 0; i < lines.length; i++) { 105 | var l = lines[i]; 106 | now_length += l.length; 107 | has_pick_count++; 108 | if(now_length > count) { 109 | if(now_length - count > 3 && has_pick_count > 1) { 110 | //如果长度超长太多,去掉最后一个填充进来的字符串。 111 | has_pick_count--; 112 | } 113 | break; 114 | } 115 | } 116 | for(var i = 0; i < has_pick_count; i++) { 117 | var s = lines.shift(); 118 | t += s; 119 | } 120 | return t; 121 | } -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | 2 | ENGLISH DOC :[click me](https://github.com/xinyu198736/js2image/blob/master/readme_en.md) 3 | 4 | EN summary: a Tool that can compress js source code to any ascii image,after that the result code can still run normal 5 | 6 | **警告:压缩后的js请人工确认后再投入生产使用,不保证100%可运行,目前测试的js以及souche.com官网的js都已经试验过,基本可以保证99%的js压缩后没有问题 7 | 8 | # who am i? 9 | 10 | **js2image** 是一个可以把`js源代码`压缩成一个`ascii字符画`的源代码的工具,它的特色是压缩后的代码仍可运行,而不是简单的拼成最终的图案。 11 | 12 | 关于js2image的原理可以见我写的这篇详解文章:[圣诞节,把网站所有的js代码都压缩成圣诞树吧。](https://zhuanlan.zhihu.com/p/20439979) 13 | 14 | # 压缩后的示例,亲测可用 15 | 16 | http://f2e.souche.com/assets/js/lib/jquery-2.1.1.min.xmas.js 17 | 18 | 另外,本项目resource目录中有多个已经跑通过的测试库文件。 19 | 20 | 压缩效果如下: 21 | 22 | ![js2image压缩效果图](http://7o52oq.com2.z0.glb.qiniucdn.com/Slice%201.png) 23 | 24 | 25 | # 安装依赖的系统模块 graphicsmagick 26 | 27 | ```bash 28 | # Ubuntu 29 | $ sudo apt-get install graphicsmagick 30 | 31 | # Fedora 32 | $ sudo dnf install GraphicsMagick 33 | 34 | # OS X 35 | $ brew install graphicsmagick 36 | 37 | # Chocolatey (package manager for Windows) 38 | # (Restart of cmd/PowerShell is required) 39 | $ choco install graphicsmagick 40 | ``` 41 | 42 | # 命令行工具使用方法 43 | 44 | 执行以下命令安装全局命令: 45 | 46 | ```bash 47 | $ npm install js2image -g 48 | ``` 49 | 50 | 使用方法: 51 | 52 | ```bash 53 | # 直接在命令行里执行此命令即可压缩,默认压缩出一个xmas.js后缀的文件。 54 | # -s 源代码路径 必须的参数! 55 | # -r 是否反相图像 可省 56 | # -i 指定使用的图片的路径,默认使用 ./resource/tree.png 可省 57 | 58 | $ js2image -s ./resource/jquery.js 59 | 60 | # 新增支持打包一个文件夹内所有js文件,慎用!不保证打包后的js100%运行正常,请经过人工测试确认。 61 | $ js2image -s ./resource 62 | 63 | $ js2image -s ./resource/jquery.js -i ./resource/tree.png 64 | ``` 65 | 66 | # 注意 67 | 68 | * 图片需要是白底的,不能是透明的 69 | * 不支持 windows 系统 70 | 71 | # 在Node.js中使用 72 | 73 | 执行以下命令安装模块: 74 | 75 | ```bash 76 | $ npm install js2image --save 77 | ``` 78 | 79 | 使用方法(见 example/test.js ): 80 | 81 | ```javascript 82 | var Js2Image = require('js2image'); 83 | 84 | var image = './resource/tree.png'; 85 | var source = './resource/jquery.js'; 86 | var target = './target/xmas.js'; 87 | var options = {}; 88 | 89 | // 获取结果的code 90 | var sourceCode = fs.readFileSync(source); 91 | Js2Image.getCode(sourceCode, image, options).then(function (code) { 92 | // code为生成的代码 93 | console.log(code); 94 | }) 95 | 96 | // 或者直接写入文件 97 | Js2Image.writeToFile(source, image, target, options).then(function (code) { 98 | // 生成的代码已被写入到文件target 99 | // code为生成的代码 100 | console.log(code); 101 | }); 102 | ``` 103 | 104 | **关于 options 可用值(可以调节像素等参数)**: 105 | 106 | **Size Options**: 107 | 108 | - `pxWidth` (Number): The pixel width used for aspect ratio (default: `2`). 109 | - `size` (Object): The size of the result image (ASCII art)—interpreted by 110 | [`compute-size`](https://github.com/IonicaBizau/compute-size): 111 | - `height` (Number|String): The height value (default: `"100%"`). 112 | - `width` (Number|String): The width value (default: computed value to 113 | keep aspect ratio). This is optional if the height is provided. 114 | - `size_options` (Object): The options for 115 | [`compute-size`](https://github.com/IonicaBizau/compute-size): 116 | - `screen_size` (Object): The screen size (defaults to terminal width 117 | and height): 118 | - `width` (Number): The screen width. 119 | - `height` (Number): The screen height. 120 | - `px_size` (Object): The pixel size. 121 | - `width` (default: `1`) 122 | - `height` (default: `1`) 123 | - `preserve_aspect_ratio` (Boolean): If `false`, the aspect ratio will 124 | not be preserved (default: `true`). 125 | - `fit_screen` (Boolean): If `false`, the result size will not fit to 126 | screen (default: `true`). 127 | 128 | **Matrix asciifier options**: 129 | 130 | - `stringify` (Boolean): If `false`, the pixel objects will not be 131 | stringified. 132 | - `concat` (Boolean): If `false`, the pixel objects will not be joined 133 | together. 134 | 135 | **Pixel asciifier options**: 136 | 137 | - `pixels` (Array|String): An array or string containing the characters 138 | used for converting the pixels in strings 139 | (default: `" .,:;i1tfLCG08@"`). 140 | - `reverse` (Boolean): If `true`, the pixels will be reversed creating a 141 | *negative image* effect (default: `false`). 142 | - `colored` (Boolean): If `true`, the output will contain ANSI styles 143 | (default: `true`). 144 | - `bg` (Boolean): If `true`, the **background** color will be used for 145 | coloring (default: false). 146 | - `fg` (Boolean): If `true`, the **foreground** color will be used for 147 | coloring (default: true). 148 | - `white_bg` (Boolean): Turn on the white background for transparent 149 | pixels (default: `true`). 150 | - `px_background` (Object): An object containing the `r` (red), `g` 151 | (green) and `b` (blue) values of the custom background color. 152 | 153 | **Other options**: 154 | 155 | - `image_type` (String): Use this to explicitely provide the image type. 156 | - `stringify_fn` (Function): A function getting the `pixels` matrix and 157 | the `options` in the arguments. Use this option to implement your own 158 | stringifier. 159 | 160 | #others 161 | 162 | 有网友反馈某些电脑上会报错,还没搞清楚情况. 163 | ``` 164 | onverting ./resource/release.js 165 | [Error: Could not execute GraphicsMagick/ImageMagick: gm "identify" "-ping" "-format" "%wx%h" "/usr/local/lib/node_modules/js2image/resource/tree.png" 166 | this most likely means the gm/convert binaries can't be found] 167 | /usr/local/lib/node_modules/js2image/utils/image-to-struct.js:19 168 | var content = converted.replace(/\S\[0m/g,"").replace(/\n/g,"\",\n\""); 169 | ^ 170 | 171 | TypeError: Cannot read property 'replace' of undefined 172 | ``` 173 | 如遇此种情况,执行以下命令即可,至于是为毛,我也没搞清楚. 174 | ``` 175 | npm install -g replace 176 | ``` 177 | -------------------------------------------------------------------------------- /resource/mustache.xmas.js: -------------------------------------------------------------------------------- 1 | /* generated by https://github.com/xinyu198736/js2image */ 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | (function(e,t ){if(typeof 13 | exports === ( "objec"+"t") && exports){t (exports)}else{var n={};t(n );if(typeof define === ("funct" 14 | +"ion") && define .amd){define(n)}else{e.Mustache=n}} })(this,function(e){var t= /\s*/ ;var n= /\s+/ ;var i= /\S/ ;var r= 15 | /\s*=/ ;var o= /\s*\}/ ;var s= /#|\^|\/|>|\{|&|=|!/ ;var a=RegExp.prototype.test;function u(e,t) { return a.call (e,t)}function l( 16 | e){ return!u (i,e)}var f=Object.prototype.toString;var c=Array. isArray || function(e){ return f.call (e) === ("[obje"+"ct Ar"+"ray]") }; 17 | function d(e){ return typeof e === ("funct"+"ion") }function h(e){ return e.replace ( /[\-\[\]{}()*+?.,\\\^$|#\s]/g , ( 18 | "\\$&") )}var p={ "&" : ( "&") , "<" : ("<") , ">" : (">") , '"' : ("""+";") , "'" : ("'") , "/" : ("/" +";") };function m(e){ return String 19 | (e).replace( /[&<>"'\/]/g , function(e){ return p [e] })}function g(e){if(!c(e) || e.length !== 2){ throw new Error ( ("Inval" +"id ta"+"gs: ") +e)} return[new 20 | RegExp(h(e[0])+ ("\\s*") ),new RegExp( ("\\s*") +h(e[1]))]} function y(i,a){a=a || e.tags;i=i || ("") ;if (typeof a === ("strin" +"g") ){a=a.split(n)}var u=g(a);var 21 | f=new x(i);var c=[];var d=[];var p=[];var m=false;var y=false; function w(){if(m && !y) {while(p.length){delete d[p.pop()]}}else{p=[]} m=false;y=false}var T,_,k,C,D,S;while 22 | (!f.eos()){T=f.pos;k=f.scanUntil(u[0]);if (k){for(var N=0,E=k. length;N0? i[i.length-1][4]:t;break 31 | ;default:n.push(r)}} return t }function x(e){ this.string=e;this.tail=e ;this.pos=0}x.prototype. eos=function(){ return this.tail === ( 32 | "") };x.prototype. scan=function(e){var t=this.tail.match(e);if( t && t.index === 0){var n=t [0];this.tail=this .tail.substring(n.length 33 | );this.pos += n.length; return n } return"" };x. prototype. scanUntil=function(e){var t=this.tail.search (e),n;switch(t){case-1: 34 | n=this.tail;this.tail= ( "") ;break;case 0:n= ("" ) ;break;default:n=this. tail.substring(0,t);this. tail=this.tail. substring(t)}this.pos += 35 | n.length; return n }; function w(e,t){this. view=e == null?{}:e;this .cache={ "." :this.view}; this.parent=t}w. prototype.push=function( 36 | e){ return new w(e,this )};w.prototype. lookup=function(e){var t ;if(e in this.cache){t=this .cache[e]}else{var n=this;while(n){if(e. 37 | indexOf( (".") )>0){t=n. view;var i=e.split( ("." ) ),r=0;while(t!=null && r" :if(!i) continue;l=this.parse(d( i)?i(u[1]):i[u[1]]);if( l!=null)o += this. renderTokens(l,n,i,r);break;case "&" :l=n.lookup(u[1]);if( 47 | l!=null)o += l;break;case "name" :l=n.lookup(u[1] );if(l!=null)o += e.escape (l);break;case "text" :o += u[1];break}} return o };e.name= ("musta"+"che.j"+"s") ; 48 | e.version= ("0.8.0") ;e. tags=[ ("{{") , ("}}") ] ;var _=new T;e. clearCache=function(){ return _.clearCache ()};e.parse=function(e,t){ 49 | return _.parse (e,t)};e. render=function(e,t,n){ return _.render (e,t,n) };e.to_html=function(t,n,i ,r){var o=e.render(t,n,i);if(d(r)){r(o)}else{ return o }}; 50 | e.escape=m;e.Scanner=x;e .Context=w;e.Writer=T}) 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | -------------------------------------------------------------------------------- /utils/keep-line.js: -------------------------------------------------------------------------------- 1 | var Promise = require("bluebird"); 2 | 3 | 4 | /** 5 | * 保留字符在一行的一个对象 6 | * @type {{}} 7 | */ 8 | module.exports = { 9 | /** 10 | * 把需要保留在一行的字符串从整个字符串中抠出来,用占位符替换 11 | * @param str 12 | * @returns {*} 13 | */ 14 | pickFromCode: function (str) { 15 | return pickFromCode(str); 16 | }, 17 | result: result, 18 | /** 19 | * 从pickFromCode把不能分离的行替换回来,另外对字符串以5个字符为单位做了分离处理,防止字符串太长影响效果。 20 | * @param lines 21 | */ 22 | findBack: function (lines) { 23 | return findBack(lines); 24 | } 25 | 26 | } 27 | var result = {} 28 | /** 29 | 把字符串中的字符串正则都提取出来,用占位符表示。之后可以替换回来 30 | */ 31 | var PREFIX = "pic_and_code_to_ascii_" 32 | var placeholderIndex = 0; 33 | var double_operator = ["==", ">=", "<=", "+=", "-=", "*=", "/=", "%=", "++", "--", "&&", "||", ">>", "<<"] 34 | var three_operator = ['===', '!=='] 35 | 36 | var other_operator = ['return function', 'throw new Error'] 37 | /** 38 | return o.call(e,t) 39 | return!c(n,e) 40 | return h.call(e)==="[object Array]" 41 | return typeof e==="function" 42 | return String(e).replace(/[&<>"'\/]/g,function(e){return v[e]}) 43 | return[new RegExp(p(e[0] 44 | return this.tail==="" 45 | return"script"; 46 | 47 | 48 | return[^a-zA-Z_0-1][a-zA-Z_0-1]+ 49 | */ 50 | //根据正则保留在一行。 51 | var reg_operator = [ 52 | { 53 | start: "return\"", 54 | reg: /^return".*?"/ // return "d" 或者 return "" 55 | }, 56 | { 57 | start: "return\'", 58 | reg: /^return'.*?'/ // return 'd' 或者 return '' 59 | }, { 60 | start: "return\/", 61 | reg: /^return\/.+?\/[igm]*/ // return//g 或者 return '' 62 | }, 63 | { 64 | start: "return", 65 | reg: /^return[^a-zA-Z_0-1"'};][a-zA-Z_0-1.]+/ // return 0.1 或者 return function 或者return aaabb 66 | }, 67 | { 68 | start: "throw", 69 | reg: /^throw [a-zA-Z_0-1]+?/ //throw new 或者 throw obj 70 | } 71 | ] 72 | //向前补全 ddd++ 的情况 73 | var findPrevNotABC = function (str, index) { 74 | var i = index; 75 | var s; 76 | do { 77 | i--; 78 | s = str.charAt(i); 79 | } while(/[a-zA-Z_0-9]/.test(s)) 80 | return i + 1; 81 | } 82 | 83 | function createPlaceholder () { 84 | return " " + PREFIX + (placeholderIndex++) + " "; 85 | } 86 | 87 | function pickFromCode (str) { 88 | 89 | //从代码字符串里把所有引号里的字符串和正则抠出来。 90 | var pickStart_double = 0; 91 | var pickEnd_double = 0; 92 | var pickStart_single = 0; 93 | var pickEnd_single = 0; 94 | var pickStart_reg = 0; 95 | var pickEnd_reg = 0; 96 | var is_in_double_quot = false; 97 | var is_in_single_quot = false; 98 | var is_in_reg = false; 99 | var is_in_other = false; 100 | var pickStart_other = 0; 101 | var pickEnd_other = 0; 102 | var strs = [] 103 | 104 | //进入状态机 105 | for(var i = 0; i < str.length; i++) { 106 | var now_char = str[i]; 107 | var last_char = i > 0 ? str[i - 1] : null; 108 | var last_two_char = i > 1 ? str[i - 2] : null; 109 | var last_three_char = i > 2 ? str[i - 3] : null; 110 | var last_four_char = i > 3 ? str[i - 4] : null; 111 | var next_char = i < (str.length - 1) ? str[i + 1] : null; 112 | var next_two_char = i < (str.length - 2) ? str[i + 2] : null; 113 | var next_three_char = i < (str.length - 3) ? str[i + 3] : null; 114 | 115 | 116 | /** 117 | * 不在正则,不在引号之内,检查是否存在operator 118 | */ 119 | if(!is_in_reg && !is_in_double_quot && !is_in_single_quot) { 120 | 121 | 122 | if(three_operator.indexOf(now_char + next_char + next_two_char) != -1) { 123 | pickStart_other = i; 124 | pickEnd_other = i + 2; 125 | i += 2; 126 | strs.push({ 127 | value: str.substring(pickStart_other, pickEnd_other + 1), 128 | type: "other", 129 | start: pickStart_other, 130 | end: pickEnd_other 131 | }) 132 | continue; 133 | } else if(double_operator.indexOf(now_char + next_char) != -1) { 134 | pickStart_other = i; 135 | pickEnd_other = i + 1; 136 | if(now_char + next_char == "++" || now_char + next_char == "--") { 137 | pickStart_other = findPrevNotABC(str, i); 138 | } else { 139 | 140 | } 141 | 142 | i += 1; 143 | strs.push({ 144 | value: str.substring(pickStart_other, pickEnd_other + 1), 145 | type: "other", 146 | start: pickStart_other, 147 | end: pickEnd_other 148 | }) 149 | continue; 150 | } 151 | /** 152 | function(){ 153 | return 154 | function(){} 155 | } 报错处理 156 | */ 157 | other_operator.forEach(function (o) { 158 | var s = str.substr(i, o.length) 159 | if(s == o) { 160 | pickStart_other = i; 161 | pickEnd_other = i + o.length - 1; 162 | i += o.length - 1; 163 | strs.push({ 164 | value: str.substring(pickStart_other, pickEnd_other + 1), 165 | type: "other", 166 | start: pickStart_other, 167 | end: pickEnd_other 168 | }) 169 | } 170 | }) 171 | //根据正则保留的处理 172 | reg_operator.forEach(function (o) { 173 | var start = o.start; 174 | var reg = o.reg; 175 | var s = str.substr(i, start.length) 176 | if(s == start) { 177 | //符合此正则,进入正则判断逻辑 178 | var sub = str.substring(i, str.length - 1); 179 | var match = sub.match(reg); 180 | if(match) { 181 | var m = match[0]; 182 | var s = str.substr(i, m.length) 183 | if(s == m) { 184 | pickStart_other = i; 185 | pickEnd_other = i + m.length - 1; 186 | i += m.length - 1; 187 | strs.push({ 188 | value: str.substring(pickStart_other, pickEnd_other + 1), 189 | type: "other", 190 | start: pickStart_other, 191 | end: pickEnd_other 192 | }) 193 | } 194 | } 195 | } 196 | }) 197 | 198 | //处理小数点。 0.11 11.2233 199 | if(now_char == ".") { 200 | //往前找数字 201 | var prev_nums = []; 202 | var nowI = i; 203 | nowI--; 204 | var c = nowI > 0 ? str[nowI] : null; 205 | while(/[0-9]/.test(c)) { 206 | prev_nums.unshift(c); 207 | nowI--; 208 | c = nowI > 0 ? str[nowI] : null; 209 | } 210 | //往后找数字 211 | var next_nums = []; 212 | var nowI = i; 213 | nowI++; 214 | var c = nowI < (str.length - 1) ? str[nowI] : null; 215 | while(/[0-9]/.test(c)) { 216 | next_nums.push(c); 217 | nowI++; 218 | c = nowI < (str.length - 1) ? str[nowI] : null; 219 | } 220 | if(prev_nums.length || next_nums.length) { 221 | var start = i - prev_nums.length; 222 | var end = i + next_nums.length; 223 | strs.push({ 224 | value: str.substring(start, end + 1), 225 | type: "other", 226 | start: start, 227 | end: end 228 | }) 229 | } 230 | 231 | } 232 | 233 | } 234 | //如果现在不在字符串里。 235 | if(!is_in_single_quot && !is_in_double_quot) { 236 | if(!is_in_reg) { 237 | if(now_char == "/" && last_char != "<" && !/[0-9a-zA-Z_)\]]/.test(last_char)) { 238 | //探测到字符串引号出现,首先判断不是转义的。 239 | if(last_char != "\\" && last_char != "\"" && last_char != "\'") { 240 | pickStart_reg = i; 241 | is_in_reg = true; 242 | } 243 | } 244 | } else { 245 | //如果现在在字符串里 246 | if(now_char == "/") { 247 | //探测到字符串出现,首先判断不是转义的。 248 | if(last_char != "\\" || 249 | (last_char == "\\" && last_two_char == "\\" && last_three_char != "\\") 250 | || (last_char == "\\" && last_two_char == "\\" && last_three_char == "\\" && last_four_char == "\\")) { // 251 | pickEnd_reg = i; 252 | is_in_reg = false; 253 | if("gim".indexOf(next_char) != -1) { 254 | pickEnd_reg++; 255 | if("gim".indexOf(next_two_char) != -1) { 256 | pickEnd_reg++; 257 | if("gim".indexOf(next_three_char) != -1) { 258 | pickEnd_reg++; 259 | } 260 | } 261 | } 262 | strs.push({ 263 | value: str.substring(pickStart_reg, pickEnd_reg + 1), 264 | type: "reg", 265 | start: pickStart_reg, 266 | end: pickEnd_reg 267 | }) 268 | } 269 | } 270 | } 271 | } 272 | //如果现在不在字符串里。 273 | if(!is_in_single_quot && !is_in_reg) { 274 | if(!is_in_double_quot) { 275 | if(now_char == "\"") { 276 | //探测到字符串引号出现,首先判断不是转义的。 277 | if(last_char != "\\") { 278 | pickStart_double = i; 279 | is_in_double_quot = true; 280 | } 281 | } 282 | } else { 283 | //如果现在在字符串里 284 | if(now_char == "\"") { 285 | //探测到字符串引号出现,首先判断不是转义的。 286 | if(last_char != "\\" || (last_char == "\\" && last_two_char == "\\" && last_three_char != "\\")) { 287 | pickEnd_double = i; 288 | is_in_double_quot = false; 289 | strs.push({ 290 | value: str.substring(pickStart_double, pickEnd_double + 1), 291 | type: "double", 292 | start: pickStart_double, 293 | end: pickEnd_double 294 | }) 295 | } 296 | } 297 | } 298 | } 299 | 300 | if(!is_in_double_quot && !is_in_reg) { 301 | if(!is_in_single_quot) { 302 | if(now_char == "\'") { 303 | //探测到字符串引号出现,首先判断不是转义的。 304 | if(last_char != "\\") { 305 | pickStart_single = i; 306 | is_in_single_quot = true; 307 | } 308 | } 309 | } else { 310 | //如果现在在字符串里 311 | if(now_char == "\'") { 312 | //探测到字符串引号出现,首先判断不是转义的。 313 | if(last_char != "\\" || (last_char == "\\" && last_two_char == "\\" && last_three_char != "\\")) { 314 | pickEnd_single = i; 315 | is_in_single_quot = false; 316 | strs.push({ 317 | value: str.substring(pickStart_single, pickEnd_single + 1), 318 | type: "single", 319 | start: pickStart_single, 320 | end: pickEnd_single 321 | }) 322 | } 323 | } 324 | } 325 | } 326 | 327 | } 328 | //处理下,把str中的相应部分都替换成占位符 329 | var str_arr = str.split(""); 330 | var str_result = ""; 331 | var start_offset = 0; 332 | result = {} 333 | for(var i in strs) { 334 | var s = strs[i]; 335 | var placehoder = createPlaceholder(); 336 | str_result += str.substring(start_offset, s.start); 337 | str_result += placehoder; 338 | s.placehoder = placehoder; 339 | start_offset = s.end + 1; 340 | result[placehoder] = s; 341 | } 342 | // console.log(result) 343 | str_result += str.substring(start_offset, str.length - 1); 344 | return str_result; 345 | } 346 | 347 | 348 | var findBack = function (lines) { 349 | var self = this; 350 | for(var i = 0; i < lines.length; i++) { 351 | var line = lines[i]; 352 | 353 | if(line.indexOf(PREFIX) != -1) { 354 | var line_data = result[" " + line + " "];//找回占位符的数据 355 | if(line_data.type == "double") { 356 | 357 | if(lines[i + 3] == ":") { 358 | //如果是 "dd":"dd" 不处理 359 | lines.splice(i, 1, line_data.value) 360 | } else { 361 | var arr = splitDoubleQuot(line_data.value); //拆分一下字符串 362 | lines.splice(i, 1); 363 | arr.forEach(function (a, n) { 364 | lines.splice(i + n, 0, a) //把数据插回去 365 | }) 366 | } 367 | 368 | 369 | } else if(line_data.type == "single") { 370 | // var arr = self.splitSingleQuot(line_data.value); //拆分一下字符串 371 | if(lines[i + 3] == ":") { 372 | //如果是 "dd":"dd" 不处理 373 | lines.splice(i, 1, line_data.value) 374 | } else { 375 | var arr = splitSingleQuot(line_data.value); //拆分一下字符串 376 | lines.splice(i, 1); 377 | arr.forEach(function (a, n) { 378 | lines.splice(i + n, 0, a) //把数据插回去 379 | }) 380 | } 381 | } else { 382 | lines.splice(i, 1, line_data.value) 383 | } 384 | } 385 | } 386 | } 387 | 388 | var splitDoubleQuot = function (str) { 389 | str = str.replace(/\\\\/g, "☃") 390 | var r = []; 391 | //把字符串分成三个三个的。例如"abcd" 编程 "acb"+"d" 392 | var s = str.substring(1, str.length - 1) 393 | var len = s.length; 394 | var cut_len = Math.ceil((len) / 5); 395 | r.push("(") 396 | var last_cursor = 0; 397 | 398 | while(last_cursor < len) { 399 | var l = 5; 400 | 401 | if(s.charAt(last_cursor + l - 1) == "\\") { //处理\a 402 | l++; 403 | if(s.charAt(last_cursor + l - 1) == "\\") { //处理 \\\ 404 | l++; 405 | } 406 | } 407 | //处理\x0a 408 | if(s.charAt(last_cursor + l - 1) == "x" && s.charAt(last_cursor + l - 2) == "\\") { 409 | l += 2; 410 | } 411 | var n = s.substring(last_cursor, last_cursor + l) 412 | last_cursor = last_cursor + n.length; 413 | n = n.replace(/☃/g, "\\\\"); 414 | r.push("\"" + n + "\"") 415 | 416 | r.push("+") 417 | } 418 | 419 | if(len == 0) { 420 | r.push('""') 421 | } else { 422 | r.pop() 423 | } 424 | r.push(")") 425 | return r; 426 | } 427 | var splitSingleQuot = function (str) { 428 | str = str.replace(/\\\\/g, "☃") 429 | var r = []; 430 | //把字符串分成三个三个的。例如"abcd" 编程 "acb"+"d" 431 | var s = str.substring(1, str.length - 1) 432 | var len = s.length; 433 | var cut_len = Math.ceil((len) / 5); 434 | r.push("(") 435 | var last_cursor = 0; 436 | 437 | while(last_cursor < len) { 438 | var l = 5; 439 | if(s.charAt(last_cursor + l - 1) == "\\") { //处理\a 440 | l++; 441 | if(s.charAt(last_cursor + l - 1) == "\\") { //处理 \\\ 442 | l++; 443 | } 444 | } 445 | if(s.charAt(last_cursor + l - 1) == "x" && s.charAt(last_cursor + l - 2) == "\\") { 446 | l += 2; 447 | } 448 | var n = s.substring(last_cursor, last_cursor + l) 449 | last_cursor = last_cursor + n.length; 450 | n = n.replace(/☃/g, "\\\\"); 451 | r.push("\'" + n + "\'") 452 | 453 | 454 | r.push("+") 455 | } 456 | 457 | if(len == 0) { 458 | r.push("''") 459 | } else { 460 | r.pop() 461 | } 462 | r.push(")") 463 | return r; 464 | } -------------------------------------------------------------------------------- /resource/mustache.js: -------------------------------------------------------------------------------- 1 | /*! 2 | * mustache.js - Logic-less {{mustache}} templates with JavaScript 3 | * http://github.com/janl/mustache.js 4 | */ 5 | 6 | /*global define: false*/ 7 | 8 | (function (root, factory) { 9 | if (typeof exports === "object" && exports) { 10 | factory(exports); // CommonJS 11 | } else { 12 | var mustache = {}; 13 | factory(mustache); 14 | if (typeof define === "function" && define.amd) { 15 | define(mustache); // AMD 16 | } else { 17 | root.Mustache = mustache; //