Repository: Iwasawafag/node-potrace Branch: master Commit: b86608eaf3b9 Files: 20 Total size: 119.4 KB Directory structure: gitextract_jxybqwmb/ ├── .editorconfig ├── .gitignore ├── .npmignore ├── .travis.yml ├── LICENSE ├── README.md ├── lib/ │ ├── Posterizer.js │ ├── Potrace.js │ ├── index.js │ ├── types/ │ │ ├── Bitmap.js │ │ ├── Curve.js │ │ ├── Histogram.js │ │ ├── Opti.js │ │ ├── Path.js │ │ ├── Point.js │ │ ├── Quad.js │ │ └── Sum.js │ └── utils.js ├── package.json └── test/ └── test.js ================================================ FILE CONTENTS ================================================ ================================================ FILE: .editorconfig ================================================ root = true [*] end_of_line = lf insert_final_newline = false indent_style = space indent_size = 2 ================================================ FILE: .gitignore ================================================ # Logs logs *.log npm-debug.log* # Runtime data pids *.pid *.seed # Directory for instrumented libs generated by jscoverage/JSCover lib-cov # Coverage directory used by tools like istanbul coverage # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) .grunt # node-waf configuration .lock-wscript # Compiled binary addons (http://nodejs.org/api/addons.html) build/Release # Dependency directory node_modules # Optional npm cache directory .npm # Optional REPL history .node_repl_history # JetBrains IDEs .idea # Test case output test/output*.svg ================================================ FILE: .npmignore ================================================ # Logs logs *.log npm-debug.log* # Runtime data pids *.pid *.seed # Directory for instrumented libs generated by jscoverage/JSCover lib-cov # Coverage directory used by tools like istanbul coverage # nyc test coverage .nyc_output # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) .grunt # node-waf configuration .lock-wscript # Compiled binary addons (http://nodejs.org/api/addons.html) build/Release # IDE files .project .idea *.iml # Test directory test/ ================================================ FILE: .travis.yml ================================================ language: node_js node_js: - "0.12" - "4" - "6" sudo: false ================================================ FILE: LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. {description} Copyright (C) {year} {fullname} This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. {signature of Ty Coon}, 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. ================================================ FILE: README.md ================================================ # node-potrace A NodeJS-compatible fork of [Potrace in JavaScript][potrace-by-kilobtye] with some additions, which is in turn a port of [the original Potrace][potrace] — a tool for tracing bitmaps. ## Example and demo | **Original image** | **Potrace output** | **Posterized output** | |---------------------------|------------------------------|-----------------------------------------| | ![](test/sources/yao.jpg) | ![](https://cdn.rawgit.com/tooolbox/node-potrace/9ee822d/test/example-output.svg) | ![](https://cdn.rawgit.com/tooolbox/node-potrace/9ee822d/test/example-output-posterized.svg) | (Example image inherited from [online demo of the browser version][potrace-js-demo]) ## Usage Install ```sh npm install potrace ``` Basic usage ```js var potrace = require('potrace'), fs = require('fs'); potrace.trace('./path/to/image.png', function(err, svg) { if (err) throw err; fs.writeFileSync('./output.svg', svg); }); ``` You can also provide a configuration object as a second argument. ```js var params = { background: '#49ffd2', color: 'blue', threshold: 120 }; potrace.trace('./path/to/image.png', params, function(err, svg) { /*...*/ }); ``` If you want to run Potrace algorithm multiple times on the same image with different threshold setting and merge results together in a single file - `posterize` method does exactly that. ```js potrace.posterize('./path/to/image.png', { threshold: 180, steps: 4 }, function(err, svg) { /*...*/ }); // or if you know exactly where you want to break it on different levels potrace.posterize('./path/to/image.png', { steps: [40, 85, 135, 180] }, function(err, svg) { /*...*/ }); ``` ### Advanced usage and configuration Both `trace` and `posterize` methods return instances of `Potrace` and `Posterizer` classes respectively to a callback function as third argument. You can also instantiate these classes directly: ```js var potrace = require('potrace'); // Tracing var trace = new potrace.Potrace(); // You can also pass configuration object to the constructor trace.setParameters({ threshold: 128, color: '#880000' }); trace.loadImage('path/to/image.png', function(err) { if (err) throw err; trace.getSVG(); // returns SVG document contents trace.getPathTag(); // will return just tag trace.getSymbol('traced-image'); // will return tag with given ID }); // Posterization var posterizer = new potrace.Posterize(); posterizer.loadImage('path/to/image.png', function(err) { if (err) throw err; posterizer.setParameter({ color: '#ccc', background: '#222', steps: 3, threshold: 200, fillStrategy: potrace.Posterize.FILL_MEAN }); posterizer.getSVG(); // or posterizer.getSymbol('posterized-image'); }); ``` Callback function provided to `loadImage` methods will be executed in context of the `Potrace`/`Posterizer` instance, so if it doesn't go against your code style - you can just do ```js new potrace.Potrace() .loadImage('path/to/image.bmp', function() { if (err) throw err; this.getSymbol('foo'); }); ``` [Jimp module][jimp] is used on the back end, so first argument accepted by `loadImage` method could be anything Jimp can read: a `Buffer`, local path or a url string. Supported formats are: PNG, JPEG or BMP. It also could be a Jimp instance (provided bitmap is not modified) ### Parameters `Potrace` class expects following parameters: - **turnPolicy** - how to resolve ambiguities in path decomposition. Possible values are exported as constants: `TURNPOLICY_BLACK`, `TURNPOLICY_WHITE`, `TURNPOLICY_LEFT`, `TURNPOLICY_RIGHT`, `TURNPOLICY_MINORITY`, `TURNPOLICY_MAJORITY`. Refer to [this document][potrace-algorithm] for more information (page 4) (default: `TURNPOLICY_MINORITY`) - **turdSize** - suppress speckles of up to this size (default: 2) - **alphaMax** - corner threshold parameter (default: 1) - **optCurve** - curve optimization (default: true) - **optTolerance** - curve optimization tolerance (default: 0.2) - **threshold** - threshold below which color is considered black. Should be a number in range 0..255 or `THRESHOLD_AUTO` in which case threshold will be selected automatically using [Algorithm For Multilevel Thresholding][multilevel-thresholding] (default: `THRESHOLD_AUTO`) - **blackOnWhite** - specifies colors by which side from threshold should be turned into vector shape (default: `true`) - **color** - Fill color. Will be ignored when exporting as \. (default: `COLOR_AUTO`, which means black or white, depending on `blackOnWhite` property) - **background** - Background color. Will be ignored when exporting as \. By default is not present (`COLOR_TRANSPARENT`) --------------- `Posterizer` class has same methods as `Potrace`, in exception of `.getPathTag()`. Configuration object is extended with following properties: - **fillStrategy** - determines how fill color for each layer should be selected. Possible values are exported as constants: - `FILL_DOMINANT` - most frequent color in range (used by default), - `FILL_MEAN` - arithmetic mean (average), - `FILL_MEDIAN` - median color, - `FILL_SPREAD` - ignores color information of the image and just spreads colors equally in range 0..\ (or \..255 if `blackOnWhite` is set to `false`), - **rangeDistribution** - how color stops for each layer should be selected. Ignored if `steps` is an array. Possible values are: - `RANGES_AUTO` - Performs automatic thresholding (using [Algorithm For Multilevel Thresholding][multilevel-thresholding]). Preferable method for already posterized sources, but takes long time to calculate 5 or more thresholds (exponential time complexity) *(used by default)* - `RANGES_EQUAL` - Ignores color information of the image and breaks available color space into equal chunks - **steps** - Specifies desired number of layers in resulting image. If a number provided - thresholds for each layer will be automatically calculated according to `rangeDistribution` parameter. If an array provided it expected to be an array with precomputed thresholds for each layer (in range 0..255) (default: `STEPS_AUTO` which will result in `3` or `4`, depending on `threshold` value) - **threshold** - Breaks image into foreground and background (and only foreground being broken into desired number of layers). Basically when provided it becomes a threshold for last (least opaque) layer and then `steps - 1` intermediate thresholds calculated. If **steps** is an array of thresholds and every value from the array is lower (or larger if **blackOnWhite** parameter set to `false`) than threshold - threshold will be added to the array, otherwise just ignored. (default: `Potrace.THRESHOLD_AUTO`) - *all other parameters that Potrace class accepts* **Notes:** - When number of `steps` is greater than 10 - an extra layer could be added to ensure presence of darkest/brightest colors if needed to ensure presence of probably-important-at-this-point details like shadows or line art. - With big number of layers produced image will be looking brighter overall than original due to math error at the rendering phase because of how layers are composited. - With default configuration `steps`, `threshold` and `rangeDistribution` settings all set to auto, resulting in a 4 thresholds/color stops being calculated with Multilevel Thresholding algorithm mentioned above. Calculation of 4 thresholds takes 3-5 seconds on average laptop. You may want to explicitly limit number of `steps` to 3 to moderately improve processing speed. ## Thanks to - Peter Selinger for [original Potrace tool and algorithm][potrace] - @kilobtye for original [javascript port][potrace-by-kilobtye] ## License The GNU General Public License version 2 (GPLv2). Please see [License File](LICENSE) for more information. [potrace]: http://potrace.sourceforge.net/ [potrace-algorithm]: http://potrace.sourceforge.net/potrace.pdf [multilevel-thresholding]: http://www.iis.sinica.edu.tw/page/jise/2001/200109_01.pdf [potrace-by-kilobtye]: https://github.com/kilobtye/potrace [potrace-js-demo]: http://kilobtye.github.io/potrace/ [jimp]: https://github.com/oliver-moran/jimp ================================================ FILE: lib/Posterizer.js ================================================ 'use strict'; var Potrace = require('./Potrace'); var utils = require('./utils'); /** * Takes multiple samples using {@link Potrace} with different threshold * settings and combines output into a single file. * * @param {Posterizer~Options} [options] * @constructor */ function Posterizer(options) { this._potrace = new Potrace(); this._calculatedThreshold = null; this._params = { threshold: Potrace.THRESHOLD_AUTO, blackOnWhite: true, steps: Posterizer.STEPS_AUTO, background: Potrace.COLOR_TRANSPARENT, fillStrategy: Posterizer.FILL_DOMINANT, rangeDistribution: Posterizer.RANGES_AUTO }; if (options) { this.setParameters(options); } } // Inherit constants from Potrace class for (var key in Potrace) { if (Object.prototype.hasOwnProperty.call(Potrace, key) && key === key.toUpperCase()) { Posterizer[key] = Potrace[key]; } } Posterizer.STEPS_AUTO = -1; Posterizer.FILL_SPREAD = 'spread'; Posterizer.FILL_DOMINANT = 'dominant'; Posterizer.FILL_MEDIAN = 'median'; Posterizer.FILL_MEAN = 'mean'; Posterizer.RANGES_AUTO = 'auto'; Posterizer.RANGES_EQUAL = 'equal'; Posterizer.prototype = { /** * Fine tuning to color ranges. * * If last range (featuring most saturated color) is larger than 10% of color space (25 units) * then we want to add another color stop, that hopefully will include darkest pixels, improving presence of * shadows and line art * * @param ranges * @private */ _addExtraColorStop: function(ranges) { var blackOnWhite = this._params.blackOnWhite; var lastColorStop = ranges[ranges.length - 1]; var lastRangeFrom = blackOnWhite ? 0 : lastColorStop.value; var lastRangeTo = blackOnWhite ? lastColorStop.value : 255; if (lastRangeTo - lastRangeFrom > 25 && lastColorStop.colorIntensity !== 1) { var histogram = this._getImageHistogram(); var levels = histogram.getStats(lastRangeFrom, lastRangeTo).levels; var newColorStop = levels.mean + levels.stdDev <= 25 ? levels.mean + levels.stdDev : levels.mean - levels.stdDev <= 25 ? levels.mean - levels.stdDev : 25; var newStats = (blackOnWhite ? histogram.getStats(0, newColorStop) : histogram.getStats(newColorStop, 255)); var color = newStats.levels.mean; ranges.push({ value: Math.abs((blackOnWhite ? 0 : 255) - newColorStop), colorIntensity: isNaN(color) ? 0 : ((blackOnWhite ? 255 - color : color) / 255) }); } return ranges; }, /** * Calculates color intensity for each element of numeric array * * @param {number[]} colorStops * @returns {{ levels: number, colorIntensity: number }[]} * @private */ _calcColorIntensity: function(colorStops) { var blackOnWhite = this._params.blackOnWhite; var colorSelectionStrat = this._params.fillStrategy; var histogram = colorSelectionStrat !== Posterizer.FILL_SPREAD ? this._getImageHistogram() : null; var fullRange = Math.abs(this._paramThreshold() - (blackOnWhite ? 0 : 255)); return colorStops.map(function(threshold, index) { var nextValue = index + 1 === colorStops.length ? (blackOnWhite ? -1 : 256) : colorStops[index + 1]; var rangeStart = Math.round(blackOnWhite ? nextValue + 1 : threshold); var rangeEnd = Math.round(blackOnWhite ? threshold : nextValue - 1); var factor = index / (colorStops.length - 1); var intervalSize = rangeEnd - rangeStart; var stats = histogram.getStats(rangeStart, rangeEnd); var color = -1; if (stats.pixels === 0) { return { value: threshold, colorIntensity: 0 }; } switch (colorSelectionStrat) { case Posterizer.FILL_SPREAD: // We want it to be 0 (255 when white on black) at the most saturated end, so... color = (blackOnWhite ? rangeStart : rangeEnd) + (blackOnWhite ? 1 : -1) * intervalSize * Math.max(0.5, fullRange / 255) * factor; break; case Posterizer.FILL_DOMINANT: color = histogram.getDominantColor(rangeStart, rangeEnd, utils.clamp(intervalSize, 1, 5)); break; case Posterizer.FILL_MEAN: color = stats.levels.mean; break; case Posterizer.FILL_MEDIAN: color = stats.levels.median; break; } // We don't want colors to be too close to each other, so we introduce some spacing in between if (index !== 0) { color = blackOnWhite ? utils.clamp(color, rangeStart, rangeEnd - Math.round(intervalSize * 0.1)) : utils.clamp(color, rangeStart + Math.round(intervalSize * 0.1), rangeEnd); } return { value: threshold, colorIntensity: color === -1 ? 0 : ((blackOnWhite ? 255 - color : color) / 255) }; }); }, /** * @returns {Histogram} * @private */ _getImageHistogram: function() { return this._potrace._luminanceData.histogram(); }, /** * Processes threshold, steps and rangeDistribution parameters and returns normalized array of color stops * @returns {*} * @private */ _getRanges: function() { var steps = this._paramSteps(); if (!Array.isArray(steps)) { return this._params.rangeDistribution === Posterizer.RANGES_AUTO ? this._getRangesAuto() : this._getRangesEquallyDistributed(); } // Steps is array of thresholds and we want to preprocess it var colorStops = []; var threshold = this._paramThreshold(); var lookingForDarkPixels = this._params.blackOnWhite; steps.forEach(function(item) { if (colorStops.indexOf(item) === -1 && utils.between(item, 0, 255)) { colorStops.push(item); } }); if (!colorStops.length) { colorStops.push(threshold); } colorStops = colorStops.sort(function (a, b) { return a < b === lookingForDarkPixels ? 1 : -1; }); if (lookingForDarkPixels && colorStops[0] < threshold) { colorStops.unshift(threshold); } else if (!lookingForDarkPixels && colorStops[colorStops.length - 1] < threshold) { colorStops.push(threshold); } return this._calcColorIntensity(colorStops); }, /** * Calculates given (or lower) number of thresholds using automatic thresholding algorithm * @returns {*} * @private */ _getRangesAuto: function() { var histogram = this._getImageHistogram(); var steps = this._paramSteps(true); var colorStops; if (this._params.threshold === Potrace.THRESHOLD_AUTO) { colorStops = histogram.multilevelThresholding(steps); } else { var threshold = this._paramThreshold(); colorStops = this._params.blackOnWhite ? histogram.multilevelThresholding(steps - 1, 0, threshold) : histogram.multilevelThresholding(steps - 1, threshold, 255); if (this._params.blackOnWhite) { colorStops.push(threshold); } else { colorStops.unshift(threshold); } } if (this._params.blackOnWhite) { colorStops = colorStops.reverse(); } return this._calcColorIntensity(colorStops); }, /** * Calculates color stops and color representing each segment, returning them * from least to most intense color (black or white, depending on blackOnWhite parameter) * * @private */ _getRangesEquallyDistributed: function() { var blackOnWhite = this._params.blackOnWhite; var colorsToThreshold = blackOnWhite ? this._paramThreshold() : 255 - this._paramThreshold(); var steps = this._paramSteps(); var stepSize = colorsToThreshold / steps; var colorStops = []; var i = steps - 1, factor, threshold; while (i >= 0) { factor = i / (steps - 1); threshold = Math.min(colorsToThreshold, (i + 1) * stepSize); threshold = blackOnWhite ? threshold : 255 - threshold; i--; colorStops.push(threshold); } return this._calcColorIntensity(colorStops); }, /** * Returns valid steps value * @param {Boolean} [count=false] * @returns {number|number[]} * @private */ _paramSteps: function(count) { var steps = this._params.steps; if (Array.isArray(steps)) { return count ? steps.length : steps; } if (steps === Posterizer.STEPS_AUTO && this._params.threshold === Potrace.THRESHOLD_AUTO) { return 4; } var blackOnWhite = this._params.blackOnWhite; var colorsCount = blackOnWhite ? this._paramThreshold() : 255 - this._paramThreshold(); return steps === Posterizer.STEPS_AUTO ? (colorsCount > 200 ? 4 : 3) : Math.min(colorsCount, Math.max(2, steps)); }, /** * Returns valid threshold value * @returns {number} * @private */ _paramThreshold: function() { if (this._calculatedThreshold !== null) { return this._calculatedThreshold; } if (this._params.threshold !== Potrace.THRESHOLD_AUTO) { this._calculatedThreshold = this._params.threshold; return this._calculatedThreshold; } var twoThresholds = this._getImageHistogram().multilevelThresholding(2); this._calculatedThreshold = this._params.blackOnWhite ? twoThresholds[1] : twoThresholds[0]; this._calculatedThreshold = this._calculatedThreshold || 128; return this._calculatedThreshold; }, /** * Running potrace on the image multiple times with different thresholds and returns an array * of path tags * * @param {Boolean} [noFillColor] * @returns {string[]} * @private */ _pathTags: function(noFillColor) { var ranges = this._getRanges(); var potrace = this._potrace; var blackOnWhite = this._params.blackOnWhite; if (ranges.length >= 10) { ranges = this._addExtraColorStop(ranges); } potrace.setParameters({ blackOnWhite: blackOnWhite }); var actualPrevLayersOpacity = 0; return ranges.map(function(colorStop) { var thisLayerOpacity = colorStop.colorIntensity; if (thisLayerOpacity === 0) { return ''; } // NOTE: With big number of layers (something like 70) there will be noticeable math error on rendering side. // In Chromium at least image will end up looking brighter overall compared to the same layers painted in solid colors. // However it works fine with sane number of layers, and it's not like we can do much about it. var calculatedOpacity = (!actualPrevLayersOpacity || thisLayerOpacity === 1) ? thisLayerOpacity : ((actualPrevLayersOpacity - thisLayerOpacity) / (actualPrevLayersOpacity - 1)); calculatedOpacity = utils.clamp(parseFloat(calculatedOpacity.toFixed(3)), 0, 1); actualPrevLayersOpacity = actualPrevLayersOpacity + (1 - actualPrevLayersOpacity) * calculatedOpacity; potrace.setParameters({ threshold: colorStop.value }); var element = noFillColor ? potrace.getPathTag('') : potrace.getPathTag(); element = utils.setHtmlAttr(element, 'fill-opacity', calculatedOpacity.toFixed(3)); var canBeIgnored = calculatedOpacity === 0 || element.indexOf(' d=""') !== -1; // var c = Math.round(Math.abs((blackOnWhite ? 255 : 0) - 255 * thisLayerOpacity)); // element = utils.setHtmlAttr(element, 'fill', 'rgb('+c+', '+c+', '+c+')'); // element = utils.setHtmlAttr(element, 'fill-opacity', ''); return canBeIgnored ? '' : element; }); }, /** * Loads image. * * @param {string|Buffer|Jimp} target Image source. Could be anything that {@link Jimp} can read (buffer, local path or url). Supported formats are: PNG, JPEG or BMP * @param {Function} callback */ loadImage: function(target, callback) { var self = this; this._potrace.loadImage(target, function(err) { self._calculatedThreshold = null; callback.call(self, err); }); }, /** * Sets parameters. Accepts same object as {Potrace} * * @param {Posterizer~Options} params */ setParameters: function(params) { if (!params) { return; } this._potrace.setParameters(params); if (params.steps && !Array.isArray(params.steps) && (!utils.isNumber(params.steps) || !utils.between(params.steps, 1, 255))) { throw new Error('Bad \'steps\' value'); } for (var key in this._params) { if (this._params.hasOwnProperty(key) && params.hasOwnProperty(key)) { this._params[key] = params[key]; } } this._calculatedThreshold = null; }, /** * Returns image as tag. Always has viewBox specified * * @param {string} id */ getSymbol: function(id) { var width = this._potrace._luminanceData.width; var height = this._potrace._luminanceData.height; var paths = this._pathTags(true); return '' + paths.join('') + ''; }, /** * Generates SVG image * @returns {String} */ getSVG: function() { var width = this._potrace._luminanceData.width, height = this._potrace._luminanceData.height; var tags = this._pathTags(false); var svg = '\n\t' + (this._params.background !== Potrace.COLOR_TRANSPARENT ? '\n\t' : '') + tags.join('\n\t') + '\n'; return svg.replace(/\n(?:\t*\n)+(\t*)/g, '\n$1'); } }; module.exports = Posterizer; /** * Posterizer options * * @typedef {Potrace~Options} Posterizer~Options * @property {Number} [steps] - Number of samples that needs to be taken (and number of layers in SVG). (default: Posterizer.STEPS_AUTO, which most likely will result in 3, sometimes 4) * @property {*} [fillStrategy] - How to select fill color for color ranges - equally spread or dominant. (default: Posterizer.FILL_DOMINANT) * @property {*} [rangeDistribution] - How to choose thresholds in-between - after equal intervals or automatically balanced. (default: Posterizer.RANGES_AUTO) */ ================================================ FILE: lib/Potrace.js ================================================ 'use strict'; var Jimp = require('jimp'); var Bitmap = require('./types/Bitmap'); var Curve = require('./types/Curve'); var Point = require('./types/Point'); var Path = require('./types/Path'); var Quad = require('./types/Quad'); var Sum = require('./types/Sum'); var Opti = require('./types/Opti'); var utils = require('./utils'); /** * Potrace class * * @param {Potrace~Options} [options] * @constructor */ function Potrace (options) { this._luminanceData = null; this._pathlist = []; this._imageLoadingIdentifier = null; this._imageLoaded = false; this._processed = false; this._params = { turnPolicy: Potrace.TURNPOLICY_MINORITY, turdSize: 2, alphaMax: 1, optCurve: true, optTolerance: 0.2, threshold: Potrace.THRESHOLD_AUTO, blackOnWhite: true, color: Potrace.COLOR_AUTO, background: Potrace.COLOR_TRANSPARENT }; if (options) { this.setParameters(options); } } Potrace.COLOR_AUTO = 'auto'; Potrace.COLOR_TRANSPARENT = 'transparent'; Potrace.THRESHOLD_AUTO = -1; Potrace.TURNPOLICY_BLACK = 'black'; Potrace.TURNPOLICY_WHITE = 'white'; Potrace.TURNPOLICY_LEFT = 'left'; Potrace.TURNPOLICY_RIGHT = 'right'; Potrace.TURNPOLICY_MINORITY = 'minority'; Potrace.TURNPOLICY_MAJORITY = 'majority'; var SUPPORTED_TURNPOLICY_VALUES = [ Potrace.TURNPOLICY_BLACK, Potrace.TURNPOLICY_WHITE, Potrace.TURNPOLICY_LEFT, Potrace.TURNPOLICY_RIGHT, Potrace.TURNPOLICY_MINORITY, Potrace.TURNPOLICY_MAJORITY ]; Potrace.prototype = { /** * Creating a new {@link Path} for every group of black pixels. * @private */ _bmToPathlist: function() { var self = this, threshold = this._params.threshold, blackOnWhite = this._params.blackOnWhite, blackMap, currentPoint = new Point(0, 0), path; if (threshold === Potrace.THRESHOLD_AUTO) { threshold = this._luminanceData.histogram().autoThreshold() || 128; } blackMap = this._luminanceData.copy(function(lum) { var pastTheThreshold = blackOnWhite ? lum > threshold : lum < threshold; return pastTheThreshold ? 0 : 1; }); /** * finds next black pixel of the image * * @param {Point} point * @returns {boolean} * @private */ function findNext(point) { var i = blackMap.pointToIndex(point); while (i < blackMap.size && blackMap.data[i] !== 1) { i++; } return i < blackMap.size && blackMap.indexToPoint(i); } function majority(x, y) { var i, a, ct; for (i = 2; i < 5; i++) { ct = 0; for (a = -i + 1; a <= i - 1; a++) { ct += blackMap.getValueAt(x + a, y + i - 1) ? 1 : -1; ct += blackMap.getValueAt(x + i - 1, y + a - 1) ? 1 : -1; ct += blackMap.getValueAt(x + a - 1, y - i) ? 1 : -1; ct += blackMap.getValueAt(x - i, y + a) ? 1 : -1; } if (ct > 0) { return 1; } else if (ct < 0) { return 0; } } return 0; } function findPath(point) { var path = new Path(), x = point.x, y = point.y, dirx = 0, diry = 1, tmp; path.sign = blackMap.getValueAt(point.x, point.y) ? "+" : "-"; while (1) { path.pt.push(new Point(x, y)); if (x > path.maxX) path.maxX = x; if (x < path.minX) path.minX = x; if (y > path.maxY) path.maxY = y; if (y < path.minY) path.minY = y; path.len++; x += dirx; y += diry; path.area -= x * diry; if (x === point.x && y === point.y) break; var l = blackMap.getValueAt(x + (dirx + diry - 1 ) / 2, y + (diry - dirx - 1) / 2); var r = blackMap.getValueAt(x + (dirx - diry - 1) / 2, y + (diry + dirx - 1) / 2); if (r && !l) { if (self._params.turnPolicy === "right" || (self._params.turnPolicy === "black" && path.sign === '+') || (self._params.turnPolicy === "white" && path.sign === '-') || (self._params.turnPolicy === "majority" && majority(x, y)) || (self._params.turnPolicy === "minority" && !majority(x, y))) { tmp = dirx; dirx = -diry; diry = tmp; } else { tmp = dirx; dirx = diry; diry = -tmp; } } else if (r) { tmp = dirx; dirx = -diry; diry = tmp; } else if (!l) { tmp = dirx; dirx = diry; diry = -tmp; } } return path; } function xorPath(path){ var y1 = path.pt[0].y, len = path.len, x, y, maxX, minY, i, j, indx; for (i = 1; i < len; i++) { x = path.pt[i].x; y = path.pt[i].y; if (y !== y1) { minY = y1 < y ? y1 : y; maxX = path.maxX; for (j = x; j < maxX; j++) { indx = blackMap.pointToIndex(j, minY); blackMap.data[indx] = blackMap.data[indx] ? 0 : 1; } y1 = y; } } } // Clear path list this._pathlist = []; while (currentPoint = findNext(currentPoint)) { path = findPath(currentPoint); xorPath(path); if (path.area > self._params.turdSize) { this._pathlist.push(path); } } }, /** * Processes path list created by _bmToPathlist method creating and optimizing {@link Curve}'s * @private */ _processPath: function() { var self = this; function calcSums(path) { var i, x, y; path.x0 = path.pt[0].x; path.y0 = path.pt[0].y; path.sums = []; var s = path.sums; s.push(new Sum(0, 0, 0, 0, 0)); for(i = 0; i < path.len; i++){ x = path.pt[i].x - path.x0; y = path.pt[i].y - path.y0; s.push(new Sum(s[i].x + x, s[i].y + y, s[i].xy + x * y, s[i].x2 + x * x, s[i].y2 + y * y)); } } function calcLon(path) { var n = path.len, pt = path.pt, dir, pivk = new Array(n), nc = new Array(n), ct = new Array(4); path.lon = new Array(n); var constraint = [new Point(), new Point()], cur = new Point(), off = new Point(), dk = new Point(), foundk; var i, j, k1, a, b, c, d, k = 0; for(i = n - 1; i >= 0; i--){ if (pt[i].x != pt[k].x && pt[i].y != pt[k].y) { k = i + 1; } nc[i] = k; } for (i = n - 1; i >= 0; i--) { ct[0] = ct[1] = ct[2] = ct[3] = 0; dir = (3 + 3 * (pt[utils.mod(i + 1, n)].x - pt[i].x) + (pt[utils.mod(i + 1, n)].y - pt[i].y)) / 2; ct[dir]++; constraint[0].x = 0; constraint[0].y = 0; constraint[1].x = 0; constraint[1].y = 0; k = nc[i]; k1 = i; while (1) { foundk = 0; dir = (3 + 3 * utils.sign(pt[k].x - pt[k1].x) + utils.sign(pt[k].y - pt[k1].y)) / 2; ct[dir]++; if (ct[0] && ct[1] && ct[2] && ct[3]) { pivk[i] = k1; foundk = 1; break; } cur.x = pt[k].x - pt[i].x; cur.y = pt[k].y - pt[i].y; if (utils.xprod(constraint[0], cur) < 0 || utils.xprod(constraint[1], cur) > 0) { break; } if (Math.abs(cur.x) <= 1 && Math.abs(cur.y) <= 1) { } else { off.x = cur.x + ((cur.y >= 0 && (cur.y > 0 || cur.x < 0)) ? 1 : -1); off.y = cur.y + ((cur.x <= 0 && (cur.x < 0 || cur.y < 0)) ? 1 : -1); if (utils.xprod(constraint[0], off) >= 0) { constraint[0].x = off.x; constraint[0].y = off.y; } off.x = cur.x + ((cur.y <= 0 && (cur.y < 0 || cur.x < 0)) ? 1 : -1); off.y = cur.y + ((cur.x >= 0 && (cur.x > 0 || cur.y < 0)) ? 1 : -1); if (utils.xprod(constraint[1], off) <= 0) { constraint[1].x = off.x; constraint[1].y = off.y; } } k1 = k; k = nc[k1]; if (!utils.cyclic(k, i, k1)) { break; } } if (foundk === 0) { dk.x = utils.sign(pt[k].x-pt[k1].x); dk.y = utils.sign(pt[k].y-pt[k1].y); cur.x = pt[k1].x - pt[i].x; cur.y = pt[k1].y - pt[i].y; a = utils.xprod(constraint[0], cur); b = utils.xprod(constraint[0], dk); c = utils.xprod(constraint[1], cur); d = utils.xprod(constraint[1], dk); j = 10000000; if (b < 0) { j = Math.floor(a / -b); } if (d > 0) { j = Math.min(j, Math.floor(-c / d)); } pivk[i] = utils.mod(k1+j,n); } } j=pivk[n-1]; path.lon[n-1]=j; for (i=n-2; i>=0; i--) { if (utils.cyclic(i+1,pivk[i],j)) { j=pivk[i]; } path.lon[i]=j; } for (i=n-1; utils.cyclic(utils.mod(i+1,n),j,path.lon[i]); i--) { path.lon[i] = j; } } function bestPolygon(path) { function penalty3(path, i, j) { var n = path.len, pt = path.pt, sums = path.sums; var x, y, xy, x2, y2, k, a, b, c, s, px, py, ex, ey, r = 0; if (j>=n) { j -= n; r = 1; } if (r === 0) { x = sums[j+1].x - sums[i].x; y = sums[j+1].y - sums[i].y; x2 = sums[j+1].x2 - sums[i].x2; xy = sums[j+1].xy - sums[i].xy; y2 = sums[j+1].y2 - sums[i].y2; k = j+1 - i; } else { x = sums[j+1].x - sums[i].x + sums[n].x; y = sums[j+1].y - sums[i].y + sums[n].y; x2 = sums[j+1].x2 - sums[i].x2 + sums[n].x2; xy = sums[j+1].xy - sums[i].xy + sums[n].xy; y2 = sums[j+1].y2 - sums[i].y2 + sums[n].y2; k = j+1 - i + n; } px = (pt[i].x + pt[j].x) / 2.0 - pt[0].x; py = (pt[i].y + pt[j].y) / 2.0 - pt[0].y; ey = (pt[j].x - pt[i].x); ex = -(pt[j].y - pt[i].y); a = ((x2 - 2*x*px) / k + px*px); b = ((xy - x*py - y*px) / k + px*py); c = ((y2 - 2*y*py) / k + py*py); s = ex*ex*a + 2*ex*ey*b + ey*ey*c; return Math.sqrt(s); } var i, j, m, k, n = path.len, pen = new Array(n + 1), prev = new Array(n + 1), clip0 = new Array(n), clip1 = new Array(n + 1), seg0 = new Array (n + 1), seg1 = new Array(n + 1), thispen, best, c; for (i=0; i0; j--) { seg1[j] = i; i = clip1[i]; } seg1[0] = 0; pen[0]=0; for (j=1; j<=m; j++) { for (i=seg1[j]; i<=seg0[j]; i++) { best = -1; for (k=seg0[j-1]; k>=clip1[i]; k--) { thispen = penalty3(path, k, i) + pen[k]; if (best < 0 || thispen < best) { prev[i] = k; best = thispen; } } pen[i] = best; } } path.m = m; path.po = new Array(m); for (i=n, j=m-1; i>0; j--) { i = prev[i]; path.po[j] = i; } } function adjustVertices(path) { function pointslope(path, i, j, ctr, dir) { var n = path.len, sums = path.sums, x, y, x2, xy, y2, k, a, b, c, lambda2, l, r=0; while (j>=n) { j-=n; r+=1; } while (i>=n) { i-=n; r-=1; } while (j<0) { j+=n; r-=1; } while (i<0) { i+=n; r+=1; } x = sums[j+1].x-sums[i].x+r*sums[n].x; y = sums[j+1].y-sums[i].y+r*sums[n].y; x2 = sums[j+1].x2-sums[i].x2+r*sums[n].x2; xy = sums[j+1].xy-sums[i].xy+r*sums[n].xy; y2 = sums[j+1].y2-sums[i].y2+r*sums[n].y2; k = j+1-i+r*n; ctr.x = x/k; ctr.y = y/k; a = (x2-x*x/k)/k; b = (xy-x*y/k)/k; c = (y2-y*y/k)/k; lambda2 = (a+c+Math.sqrt((a-c)*(a-c)+4*b*b))/2; a -= lambda2; c -= lambda2; if (Math.abs(a) >= Math.abs(c)) { l = Math.sqrt(a*a+b*b); if (l!==0) { dir.x = -b/l; dir.y = a/l; } } else { l = Math.sqrt(c*c+b*b); if (l!==0) { dir.x = -c/l; dir.y = b/l; } } if (l===0) { dir.x = dir.y = 0; } } var m = path.m, po = path.po, n = path.len, pt = path.pt, x0 = path.x0, y0 = path.y0, ctr = new Array(m), dir = new Array(m), q = new Array(m), v = new Array(3), d, i, j, k, l, s = new Point(); path.curve = new Curve(m); for (i=0; iQ.at(1, 1)) { v[0] = -Q.at(0, 1); v[1] = Q.at(0, 0); } else if (Q.at(1, 1)) { v[0] = -Q.at(1, 1); v[1] = Q.at(1, 0); } else { v[0] = 1; v[1] = 0; } d = v[0] * v[0] + v[1] * v[1]; v[2] = - v[1] * s.y - v[0] * s.x; for (l=0; l<3; l++) { for (k=0; k<3; k++) { Q.data[l * 3 + k] += v[l] * v[k] / d; } } } dx = Math.abs(w.x-s.x); dy = Math.abs(w.y-s.y); if (dx <= 0.5 && dy <= 0.5) { path.curve.vertex[i] = new Point(w.x+x0, w.y+y0); continue; } min = utils.quadform(Q, s); xmin = s.x; ymin = s.y; if (Q.at(0, 0) !== 0.0) { for (z=0; z<2; z++) { w.y = s.y-0.5+z; w.x = - (Q.at(0, 1) * w.y + Q.at(0, 2)) / Q.at(0, 0); dx = Math.abs(w.x-s.x); cand = utils.quadform(Q, w); if (dx <= 0.5 && cand < min) { min = cand; xmin = w.x; ymin = w.y; } } } if (Q.at(1, 1) !== 0.0) { for (z=0; z<2; z++) { w.x = s.x-0.5+z; w.y = - (Q.at(1, 0) * w.x + Q.at(1, 2)) / Q.at(1, 1); dy = Math.abs(w.y-s.y); cand = utils.quadform(Q, w); if (dy <= 0.5 && cand < min) { min = cand; xmin = w.x; ymin = w.y; } } } for (l=0; l<2; l++) { for (k=0; k<2; k++) { w.x = s.x-0.5+l; w.y = s.y-0.5+k; cand = utils.quadform(Q, w); if (cand < min) { min = cand; xmin = w.x; ymin = w.y; } } } path.curve.vertex[i] = new Point(xmin + x0, ymin + y0); } } function reverse(path) { var curve = path.curve, m = curve.n, v = curve.vertex, i, j, tmp; for (i=0, j=m-1; i1 ? (1 - 1.0/dd) : 0; alpha = alpha / 0.75; } else { alpha = 4/3.0; } curve.alpha0[j] = alpha; if (alpha >= self._params.alphaMax) { curve.tag[j] = "CORNER"; curve.c[3 * j + 1] = curve.vertex[j]; curve.c[3 * j + 2] = p4; } else { if (alpha < 0.55) { alpha = 0.55; } else if (alpha > 1) { alpha = 1; } p2 = utils.interval(0.5+0.5*alpha, curve.vertex[i], curve.vertex[j]); p3 = utils.interval(0.5+0.5*alpha, curve.vertex[k], curve.vertex[j]); curve.tag[j] = "CURVE"; curve.c[3 * j + 0] = p2; curve.c[3 * j + 1] = p3; curve.c[3 * j + 2] = p4; } curve.alpha[j] = alpha; curve.beta[j] = 0.5; } curve.alphaCurve = 1; } function optiCurve(path) { function opti_penalty(path, i, j, res, opttolerance, convc, areac) { var m = path.curve.n, curve = path.curve, vertex = curve.vertex, k, k1, k2, conv, i1, area, alpha, d, d1, d2, p0, p1, p2, p3, pt, A, R, A1, A2, A3, A4, s, t; if (i==j) { return 1; } k = i; i1 = utils.mod(i+1, m); k1 = utils.mod(k+1, m); conv = convc[k1]; if (conv === 0) { return 1; } d = utils.ddist(vertex[i], vertex[i1]); for (k=k1; k!=j; k=k1) { k1 = utils.mod(k+1, m); k2 = utils.mod(k+2, m); if (convc[k1] != conv) { return 1; } if (utils.sign(utils.cprod(vertex[i], vertex[i1], vertex[k1], vertex[k2])) != conv) { return 1; } if (utils.iprod1(vertex[i], vertex[i1], vertex[k1], vertex[k2]) < d * utils.ddist(vertex[k1], vertex[k2]) * -0.999847695156) { return 1; } } p0 = curve.c[utils.mod(i,m) * 3 + 2].copy(); p1 = vertex[utils.mod(i+1,m)].copy(); p2 = vertex[utils.mod(j,m)].copy(); p3 = curve.c[utils.mod(j,m) * 3 + 2].copy(); area = areac[j] - areac[i]; area -= utils.dpara(vertex[0], curve.c[i * 3 + 2], curve.c[j * 3 + 2])/2; if (i>=j) { area += areac[m]; } A1 = utils.dpara(p0, p1, p2); A2 = utils.dpara(p0, p1, p3); A3 = utils.dpara(p0, p2, p3); A4 = A1+A3-A2; if (A2 == A1) { return 1; } t = A3/(A3-A4); s = A2/(A2-A1); A = A2 * t / 2.0; if (A === 0.0) { return 1; } R = area / A; alpha = 2 - Math.sqrt(4 - R / 0.3); res.c[0] = utils.interval(t * alpha, p0, p1); res.c[1] = utils.interval(s * alpha, p3, p2); res.alpha = alpha; res.t = t; res.s = s; p1 = res.c[0].copy(); p2 = res.c[1].copy(); res.pen = 0; for (k=utils.mod(i+1,m); k!=j; k=k1) { k1 = utils.mod(k+1,m); t = utils.tangent(p0, p1, p2, p3, vertex[k], vertex[k1]); if (t<-0.5) { return 1; } pt = utils.bezier(t, p0, p1, p2, p3); d = utils.ddist(vertex[k], vertex[k1]); if (d === 0.0) { return 1; } d1 = utils.dpara(vertex[k], vertex[k1], pt) / d; if (Math.abs(d1) > opttolerance) { return 1; } if (utils.iprod(vertex[k], vertex[k1], pt) < 0 || utils.iprod(vertex[k1], vertex[k], pt) < 0) { return 1; } res.pen += d1 * d1; } for (k=i; k!=j; k=k1) { k1 = utils.mod(k+1,m); t = utils.tangent(p0, p1, p2, p3, curve.c[k * 3 + 2], curve.c[k1 * 3 + 2]); if (t<-0.5) { return 1; } pt = utils.bezier(t, p0, p1, p2, p3); d = utils.ddist(curve.c[k * 3 + 2], curve.c[k1 * 3 + 2]); if (d === 0.0) { return 1; } d1 = utils.dpara(curve.c[k * 3 + 2], curve.c[k1 * 3 + 2], pt) / d; d2 = utils.dpara(curve.c[k * 3 + 2], curve.c[k1 * 3 + 2], vertex[k1]) / d; d2 *= 0.75 * curve.alpha[k1]; if (d2 < 0) { d1 = -d1; d2 = -d2; } if (d1 < d2 - opttolerance) { return 1; } if (d1 < d2) { res.pen += (d1 - d2) * (d1 - d2); } } return 0; } var curve = path.curve, m = curve.n, vert = curve.vertex, pt = new Array(m + 1), pen = new Array(m + 1), len = new Array(m + 1), opt = new Array(m + 1), om, i,j,r, o = new Opti(), p0, i1, area, alpha, ocurve, s, t; var convc = new Array(m), areac = new Array(m + 1); for (i=0; i=0; i--) { r = opti_penalty(path, i, utils.mod(j,m), o, self._params.optTolerance, convc, areac); if (r) { break; } if (len[j] > len[i]+1 || (len[j] == len[i]+1 && pen[j] > pen[i] + o.pen)) { pt[j] = i; pen[j] = pen[i] + o.pen; len[j] = len[i] + 1; opt[j] = o; o = new Opti(); } } } om = len[m]; ocurve = new Curve(om); s = new Array(om); t = new Array(om); j = m; for (i=om-1; i>=0; i--) { if (pt[j]==j-1) { ocurve.tag[i] = curve.tag[utils.mod(j,m)]; ocurve.c[i * 3 + 0] = curve.c[utils.mod(j,m) * 3 + 0]; ocurve.c[i * 3 + 1] = curve.c[utils.mod(j,m) * 3 + 1]; ocurve.c[i * 3 + 2] = curve.c[utils.mod(j,m) * 3 + 2]; ocurve.vertex[i] = curve.vertex[utils.mod(j,m)]; ocurve.alpha[i] = curve.alpha[utils.mod(j,m)]; ocurve.alpha0[i] = curve.alpha0[utils.mod(j,m)]; ocurve.beta[i] = curve.beta[utils.mod(j,m)]; s[i] = t[i] = 1.0; } else { ocurve.tag[i] = "CURVE"; ocurve.c[i * 3 + 0] = opt[j].c[0]; ocurve.c[i * 3 + 1] = opt[j].c[1]; ocurve.c[i * 3 + 2] = curve.c[utils.mod(j,m) * 3 + 2]; ocurve.vertex[i] = utils.interval(opt[j].s, curve.c[utils.mod(j,m) * 3 + 2], vert[utils.mod(j,m)]); ocurve.alpha[i] = opt[j].alpha; ocurve.alpha0[i] = opt[j].alpha; s[i] = opt[j].s; t[i] = opt[j].t; } j = pt[j]; } for (i=0; i tag without rest of the SVG file * * @param {String} [fillColor] - overrides color from parameters * @returns {String} */ getPathTag: function(fillColor) { fillColor = arguments.length === 0 ? this._params.color : fillColor; if (fillColor === Potrace.COLOR_AUTO) { fillColor = this._params.blackOnWhite ? 'black' : 'white'; } if (!this._imageLoaded) { throw new Error('Image should be loaded first'); } if (!this._processed) { this._bmToPathlist(); this._processPath(); this._processed = true; } var tag = ''; return tag; }, /** * Returns tag. Always has viewBox specified and comes with no fill color, * so it could be changed with tag * * @param id * @returns {string} */ getSymbol: function(id) { return '' + this.getPathTag('') + ''; }, /** * Generates SVG image * @returns {String} */ getSVG: function() { var width = this._luminanceData.width; var height = this._luminanceData.height; return '\n'+ (this._params.background !== Potrace.COLOR_TRANSPARENT ? '\t\n' : '') + '\t' + this.getPathTag(this._params.color) + '\n' + ''; } }; module.exports = Potrace; /** * Potrace options * * @typedef {Object} Potrace~Options * @property {*} [turnPolicy] - how to resolve ambiguities in path decomposition (default Potrace.TURNPOLICY_MINORITY) * @property {Number} [turdSize] - suppress speckles of up to this size (default 2) * @property {Number} [alphaMax] - corner threshold parameter (default 1) * @property {Boolean} [optCurve] - curve optimization (default true) * @property {Number} [optTolerance] - curve optimization tolerance (default 0.2) * @property {Number} [threshold] - threshold below which color is considered black (0..255, default Potrace.THRESHOLD_AUTO) * @property {Boolean} [blackOnWhite] - specifies colors by which side from threshold should be traced (default true) * @property {string} [color] - foreground color (default: 'auto' (black or white)) Will be ignored when exporting as * @property {string} [background] - background color (default: 'transparent') Will be ignored when exporting as */ /** * Jimp module * @external Jimp * @see https://www.npmjs.com/package/jimp */ ================================================ FILE: lib/index.js ================================================ 'use strict'; var Potrace = require('./Potrace'); var Posterizer = require('./Posterizer'); /** * Wrapper for Potrace that simplifies use down to one function call * * @param {string|Buffer|Jimp} file Source image, file path or {@link Jimp} instance * @param {Potrace~Options} [options] * @param {traceCallback} cb Callback function. Accepts 3 arguments: error, svg content and instance of {@link Potrace} (so it could be reused with different set of parameters) */ function trace(file, options, cb) { if (arguments.length === 2) { cb = options; options = {}; } var potrace = new Potrace(options); potrace.loadImage(file, function(err) { if (err) { return cb(err); } cb(null, potrace.getSVG(), potrace); }); } /** * Wrapper for Potrace that simplifies use down to one function call * * @param {string|Buffer|Jimp} file Source image, file path or {@link Jimp} instance * @param {Posterizer~Options} [options] * @param {posterizeCallback} cb Callback function. Accepts 3 arguments: error, svg content and instance of {@link Potrace} (so it could be reused with different set of parameters) */ function posterize(file, options, cb) { if (arguments.length === 2) { cb = options; options = {}; } var posterizer = new Posterizer(options); posterizer.loadImage(file, function(err) { if (err) { return cb(err); } cb(null, posterizer.getSVG(), posterizer); }); } module.exports = { trace: trace, posterize: posterize, Potrace: Potrace, Posterizer: Posterizer }; /** * Callback for trace method * @callback traceCallback * @param {Error|null} err * @param {string} svg SVG document contents * @param {Potrace} [instance] Potrace class instance */ /** * Callback for posterize method * @callback posterizeCallback * @param {Error|null} err * @param {string} svg SVG document contents * @param {Posterizer} [instance] Posterizer class instance */ ================================================ FILE: lib/types/Bitmap.js ================================================ 'use strict'; var Point = require('./Point'); var utils = require('../utils'); var Histogram; /** * Represents a bitmap where each pixel can be a number in range of 0..255 * Used internally to store luminance data. * * @param {Number} w * @param {Number} h * @constructor */ function Bitmap(w, h) { this._histogram = null; this.width = w; this.height = h; this.size = w * h; this.arrayBuffer = new ArrayBuffer(this.size); this.data = new Uint8Array(this.arrayBuffer); } module.exports = Bitmap; Histogram = require('./Histogram'); Bitmap.prototype = { /** * Returns pixel value * * @param {Number|Point} x - index, point or x * @param {Number} [y] */ getValueAt: function(x, y) { var index = (typeof x === 'number' && typeof y !== 'number') ? x : this.pointToIndex(x, y); return this.data[index]; }, /** * Converts {@link Point} to index value * * @param {Number} index * @returns {Point} */ indexToPoint: function(index) { var point = new Point(); if (utils.between(index, 0, this.size)) { point.y = Math.floor(index / this.width); point.x = index - point.y * this.width; } else { point.x = -1; point.y = -1; } return point; }, /** * Calculates index for point or coordinate pair * * @param {Number|Point} pointOrX * @param {Number} [y] * @returns {Number} */ pointToIndex: function(pointOrX, y) { var _x = pointOrX, _y = y; if (pointOrX instanceof Point) { _x = pointOrX.x; _y = pointOrX.y; } if (!utils.between(_x, 0, this.width) || !utils.between(_y, 0, this.height)) { return -1; } return this.width * _y + _x; }, /** * Makes a copy of current bitmap * * @param {Function} [iterator] optional callback, used for processing pixel value. Accepted arguments: value, index * @returns {Bitmap} */ copy: function(iterator) { var bm = new Bitmap(this.width, this.height), iteratorPresent = typeof iterator === 'function', i; for (i = 0; i < this.size; i++) { bm.data[i] = iteratorPresent ? iterator(this.data[i], i) : this.data[i]; } return bm; }, histogram: function() { var Histogram = require('./Histogram'); if (this._histogram) { return this._histogram; } this._histogram = new Histogram(this); return this._histogram; } }; ================================================ FILE: lib/types/Curve.js ================================================ 'use strict'; /** * Curve type * * @param n * @constructor * @protected */ function Curve(n) { this.n = n; this.tag = new Array(n); this.c = new Array(n * 3); this.alphaCurve = 0; this.vertex = new Array(n); this.alpha = new Array(n); this.alpha0 = new Array(n); this.beta = new Array(n); } module.exports = Curve; ================================================ FILE: lib/types/Histogram.js ================================================ "use strict"; // Histogram var utils = require('../utils'); var Jimp = null; try { Jimp = require('jimp'); } catch(e) {} var Bitmap = require('./Bitmap'); var COLOR_DEPTH = 256; var COLOR_RANGE_END = COLOR_DEPTH - 1; /** * Calculates array index for pair of indexes. We multiple column (x) by 256 and then add row to it, * this way `(index(i, j) + 1) === index(i, j + i)` thus we can reuse `index(i, j)` we once calculated * * Note: this is different from how indexes calculated in {@link Bitmap} class, keep it in mind. * * @param x * @param y * @returns {*} * @private */ function index(x, y) { return COLOR_DEPTH * x + y; } function normalizeMinMax(levelMin, levelMax) { /** * Shared parameter normalization for methods 'multilevelThresholding', 'autoThreshold', 'getDominantColor' and 'getStats' * * @param levelMin * @param levelMax * @returns {number[]} * @private */ levelMin = typeof levelMin === 'number' ? utils.clamp(Math.round(levelMin), 0, COLOR_RANGE_END) : 0; levelMax = typeof levelMax === 'number' ? utils.clamp(Math.round(levelMax), 0, COLOR_RANGE_END) : COLOR_RANGE_END; if (levelMin > levelMax) { throw new Error('Invalid range "'+ levelMin + '...' + levelMax + '"'); } return [levelMin, levelMax]; } /** * 1D Histogram * * @param {Number|Bitmap|Jimp} imageSource - Image to collect pixel data from. Or integer to create empty histogram for image of specific size * @param [mode] Used only for Jimp images. {@link Bitmap} currently can only store 256 values per pixel, so it's assumed that it contains values we are looking for * @constructor * @protected */ function Histogram(imageSource, mode) { this.data = null; this.pixels = 0; this._sortedIndexes = null; this._cachedStats = {}; this._lookupTableH = null; if (typeof imageSource === 'number') { this._createArray(imageSource); } else if (imageSource instanceof Bitmap) { this._collectValuesBitmap(imageSource); } else if (Jimp && imageSource instanceof Jimp) { this._collectValuesJimp(imageSource, mode); } else { throw new Error('Unsupported image source'); } } Histogram.MODE_LUMINANCE = 'luminance'; Histogram.MODE_R = 'r'; Histogram.MODE_G = 'g'; Histogram.MODE_B = 'b'; Histogram.prototype = { /** * Initializes data array for an image of given pixel size * @param imageSize * @returns {Uint8Array|Uint16Array|Uint32Array} * @private */ _createArray: function(imageSize) { var ArrayType = imageSize <= Math.pow(2, 8) ? Uint8Array : imageSize <= Math.pow(2, 16) ? Uint16Array : Uint32Array; this.pixels = imageSize; return this.data = new ArrayType(COLOR_DEPTH); }, /** * Aggregates color data from {@link Jimp} instance * @param {Jimp} source * @param mode * @private */ _collectValuesJimp: function(source, mode) { var pixelData = source.bitmap.data; var data = this._createArray(source.bitmap.width * source.bitmap.height); source.scan(0, 0, source.bitmap.width, source.bitmap.height, function(x, y, idx) { var val = mode === Histogram.MODE_R ? pixelData[idx] : mode === Histogram.MODE_G ? pixelData[idx + 1] : mode === Histogram.MODE_B ? pixelData[idx + 2] : utils.luminance(pixelData[idx], pixelData[idx + 1], pixelData[idx + 2]); data[val]++; }); }, /** * Aggregates color data from {@link Bitmap} instance * @param {Bitmap} source * @private */ _collectValuesBitmap: function(source) { var data = this._createArray(source.size); var len = source.data.length; var color; for (var i = 0; i < len; i++) { color = source.data[i]; data[color]++ } }, /** * Returns array of color indexes in ascending order * @param refresh * @returns {*} * @private */ _getSortedIndexes: function(refresh) { if (!refresh && this._sortedIndexes) { return this._sortedIndexes; } var data = this.data; var indexes = new Array(COLOR_DEPTH); var i = 0; for (i; i < COLOR_DEPTH; i++) { indexes[i] = i; } indexes.sort(function(a, b) { return data[a] > data[b] ? 1 : data[a] < data[b] ? -1 : 0; }); this._sortedIndexes = indexes; return indexes; }, /** * Builds lookup table H from lookup tables P and S. * see {@link http://www.iis.sinica.edu.tw/page/jise/2001/200109_01.pdf|this paper} for more details * * @returns {Float64Array} * @private */ _thresholdingBuildLookupTable: function() { var P = new Float64Array(COLOR_DEPTH * COLOR_DEPTH); var S = new Float64Array(COLOR_DEPTH * COLOR_DEPTH); var H = new Float64Array(COLOR_DEPTH * COLOR_DEPTH); var pixelsTotal = this.pixels; var i, j, idx, tmp; // diagonal for (i = 1; i < COLOR_DEPTH; ++i) { idx = index(i, i); tmp = this.data[i] / pixelsTotal; P[idx] = tmp; S[idx] = i * tmp; } // calculate first row (row 0 is all zero) for (i = 1; i < COLOR_DEPTH - 1; ++i) { tmp = this.data[i + 1] / pixelsTotal; idx = index(1, i); P[idx+1] = P[idx] + tmp; S[idx+1] = S[idx] + (i + 1) * tmp; } // using row 1 to calculate others for (i = 2; i < COLOR_DEPTH; i++) { for (j=i+1; j < COLOR_DEPTH; j++) { P[index(i, j)] = P[index(1, j)] - P[index(1, i-1)]; S[index(i, j)] = S[index(1, j)] - S[index(1, i-1)]; } } // now calculate H[i][j] for (i = 1; i < COLOR_DEPTH; ++i) { for (j = i + 1; j < COLOR_DEPTH; j++) { idx = index(i, j); H[idx] = P[idx] !== 0 ? S[idx] * S[idx] / P[idx] : 0; } } return this._lookupTableH = H; }, /** * Implements Algorithm For Multilevel Thresholding * Receives desired number of color stops, returns array of said size. Could be limited to a range levelMin..levelMax * * Regardless of levelMin and levelMax values it still relies on between class variances for the entire histogram * * @param amount - how many thresholds should be calculated * @param [levelMin=0] - histogram segment start * @param [levelMax=255] - histogram segment end * @returns {number[]} */ multilevelThresholding: function (amount, levelMin, levelMax) { levelMin = normalizeMinMax(levelMin, levelMax); levelMax = levelMin[1]; levelMin = levelMin[0]; amount = Math.min(levelMax - levelMin - 2, ~~amount); if (amount < 1) { return []; } if (!this._lookupTableH) { this._thresholdingBuildLookupTable(); } var H = this._lookupTableH; var colorStops = null; var maxSig = 0; if (amount > 4) { console.log('[Warning]: Threshold computation for more than 5 levels may take a long time'); } function iterateRecursive (startingPoint, prevVariance, indexes, previousDepth) { startingPoint = (startingPoint || 0) + 1; prevVariance = prevVariance || 0; indexes = indexes || (new Array(amount)); previousDepth = previousDepth || 0; var depth = previousDepth + 1; // t var variance; for (var i = startingPoint; i < levelMax - amount + previousDepth; i++) { variance = prevVariance + H[index(startingPoint, i)]; indexes[depth - 1] = i; if (depth + 1 < amount + 1) { // we need to go deeper iterateRecursive(i, variance, indexes, depth); } else { // enough, we can compare values now variance += H[index(i + 1, levelMax)]; if (maxSig < variance) { maxSig = variance; colorStops = indexes.slice(); } } } } iterateRecursive(levelMin || 0); return colorStops ? colorStops : []; }, /** * Automatically finds threshold value using Algorithm For Multilevel Thresholding * * @param {number} [levelMin] * @param {number} [levelMax] * @returns {null|number} */ autoThreshold: function(levelMin, levelMax) { var value = this.multilevelThresholding(1, levelMin, levelMax); return value.length ? value[0] : null; }, /** * Returns dominant color in given range. Returns -1 if not a single color from the range present on the image * * @param [levelMin=0] * @param [levelMax=255] * @param [tolerance=1] * @returns {number} */ getDominantColor: function(levelMin, levelMax, tolerance) { levelMin = normalizeMinMax(levelMin, levelMax); levelMax = levelMin[1]; levelMin = levelMin[0]; tolerance = tolerance || 1; var colors = this.data, dominantIndex = -1, dominantValue = -1, i, j, tmp; if (levelMin === levelMax) { return colors[levelMin] ? levelMin : -1; } for (i=levelMin; i <= levelMax; i++) { tmp = 0; for (j = ~~(tolerance / -2); j < tolerance; j++) { tmp += utils.between(i + j, 0, COLOR_RANGE_END) ? colors[i + j] : 0; } var summIsBigger = tmp > dominantValue; var summEqualButMainColorIsBigger = dominantValue === tmp && (dominantIndex < 0 || colors[i] > colors[dominantIndex]); if (summIsBigger || summEqualButMainColorIsBigger) { dominantIndex = i; dominantValue = tmp; } } return dominantValue <= 0 ? -1 : dominantIndex; }, /** * Returns stats for histogram or its segment. * * Returned object contains median, mean and standard deviation for pixel values; * peak, mean and median number of pixels per level and few other values * * If no pixels colors from specified range present on the image - most values will be NaN * * @param {Number} [levelMin=0] - histogram segment start * @param {Number} [levelMax=255] - histogram segment end * @param {Boolean} [refresh=false] - if cached result can be returned * @returns {{levels: {mean: (number|*), median: *, stdDev: number, unique: number}, pixelsPerLevel: {mean: (number|*), median: (number|*), peak: number}, pixels: number}} */ getStats: function(levelMin, levelMax, refresh) { levelMin = normalizeMinMax(levelMin, levelMax); levelMax = levelMin[1]; levelMin = levelMin[0]; if (!refresh && this._cachedStats[levelMin + '-' + levelMax]) { return this._cachedStats[levelMin + '-' + levelMax]; } var data = this.data; var sortedIndexes = this._getSortedIndexes(); var pixelsTotal = 0; var medianValue = null; var meanValue; var medianPixelIndex; var pixelsPerLevelMean; var pixelsPerLevelMedian; var tmpSumOfDeviations = 0; var tmpPixelsIterated = 0; var allPixelValuesCombined = 0; var i, tmpPixels, tmpPixelValue; var uniqueValues = 0; // counter for levels that's represented by at least one pixel var mostPixelsPerLevel = 0; // Finding number of pixels and mean for (i = levelMin; i <= levelMax; i++) { pixelsTotal += data[i]; allPixelValuesCombined += data[i] * i; uniqueValues += data[i] === 0 ? 0 : 1; if (mostPixelsPerLevel < data[i]) { mostPixelsPerLevel = data[i]; } } meanValue = allPixelValuesCombined / pixelsTotal; pixelsPerLevelMean = pixelsTotal / (levelMax - levelMin); pixelsPerLevelMedian = pixelsTotal / uniqueValues; medianPixelIndex = Math.floor(pixelsTotal / 2); // Finding median and standard deviation for (i = 0; i < COLOR_DEPTH; i++) { tmpPixelValue = sortedIndexes[i]; tmpPixels = data[tmpPixelValue]; if (tmpPixelValue < levelMin || tmpPixelValue > levelMax) { continue; } tmpPixelsIterated += tmpPixels; tmpSumOfDeviations += Math.pow(tmpPixelValue - meanValue, 2) * tmpPixels; if (medianValue === null && tmpPixelsIterated >= medianPixelIndex) { medianValue = tmpPixelValue; } } return this._cachedStats[levelMin + '-' + levelMax] = { // various pixel counts for levels (0..255) levels: { mean: meanValue, median: medianValue, stdDev: Math.sqrt(tmpSumOfDeviations / pixelsTotal), unique: uniqueValues }, // what's visually represented as bars pixelsPerLevel: { mean: pixelsPerLevelMean, median: pixelsPerLevelMedian, peak: mostPixelsPerLevel }, pixels: pixelsTotal }; } }; module.exports = Histogram; ================================================ FILE: lib/types/Opti.js ================================================ 'use strict'; var Point = require('./Point'); function Opti() { this.pen = 0; this.c = [new Point(), new Point()]; this.t = 0; this.s = 0; this.alpha = 0; } module.exports = Opti; ================================================ FILE: lib/types/Path.js ================================================ 'use strict'; function Path() { this.area = 0; this.len = 0; this.curve = {}; this.pt = []; this.minX = 100000; this.minY = 100000; this.maxX = -1; this.maxY = -1; } module.exports = Path; ================================================ FILE: lib/types/Point.js ================================================ 'use strict'; function Point(x, y) { this.x = x || 0; this.y = y || 0; } Point.prototype = { copy: function() { return new Point(this.x, this.y); } }; module.exports = Point; ================================================ FILE: lib/types/Quad.js ================================================ 'use strict'; function Quad() { this.data = [0,0,0,0,0,0,0,0,0]; } Quad.prototype.at = function(x, y) { return this.data[x * 3 + y]; }; module.exports = Quad; ================================================ FILE: lib/types/Sum.js ================================================ 'use strict'; function Sum(x, y, xy, x2, y2) { this.x = x; this.y = y; this.xy = xy; this.x2 = x2; this.y2 = y2; } module.exports = Sum; ================================================ FILE: lib/utils.js ================================================ 'use strict'; var Point = require('./types/Point'); var attrRegexps = {}; function getAttrRegexp(attrName) { if (attrRegexps[attrName]) { return attrRegexps[attrName]; } attrRegexps[attrName] = new RegExp(' ' + attrName + '="((?:\\\\(?=")"|[^"])+)"', 'i'); return attrRegexps[attrName]; } function setHtmlAttribute(html, attrName, value) { var attr = ' ' + attrName + '="' + value + '"'; if (html.indexOf(' ' + attrName + '="') === -1) { html = html.replace(/<[a-z]+/i, function(beginning) { return beginning + attr; }); } else { html = html.replace(getAttrRegexp(attrName), attr); } return html; } function fixed(number) { return number.toFixed(3).replace('.000', ''); } function mod(a, n) { return a >= n ? a % n : a>=0 ? a : n-1-(-1-a) % n; } function xprod(p1, p2) { return p1.x * p2.y - p1.y * p2.x; } function cyclic(a, b, c) { if (a <= c) { return (a <= b && b < c); } else { return (a <= b || b < c); } } function sign(i) { return i > 0 ? 1 : i < 0 ? -1 : 0; } function quadform(Q, w) { var v = new Array(3), i, j, sum; v[0] = w.x; v[1] = w.y; v[2] = 1; sum = 0.0; for (i=0; i<3; i++) { for (j=0; j<3; j++) { sum += v[i] * Q.at(i, j) * v[j]; } } return sum; } function interval(lambda, a, b) { var res = new Point(); res.x = a.x + lambda * (b.x - a.x); res.y = a.y + lambda * (b.y - a.y); return res; } function dorth_infty(p0, p2) { var r = new Point(); r.y = sign(p2.x - p0.x); r.x = -sign(p2.y - p0.y); return r; } function ddenom(p0, p2) { var r = dorth_infty(p0, p2); return r.y * (p2.x - p0.x) - r.x * (p2.y - p0.y); } function dpara(p0, p1, p2) { var x1, y1, x2, y2; x1 = p1.x - p0.x; y1 = p1.y - p0.y; x2 = p2.x - p0.x; y2 = p2.y - p0.y; return x1 * y2 - x2 * y1; } function cprod(p0, p1, p2, p3) { var x1, y1, x2, y2; x1 = p1.x - p0.x; y1 = p1.y - p0.y; x2 = p3.x - p2.x; y2 = p3.y - p2.y; return x1 * y2 - x2 * y1; } function iprod(p0, p1, p2) { var x1, y1, x2, y2; x1 = p1.x - p0.x; y1 = p1.y - p0.y; x2 = p2.x - p0.x; y2 = p2.y - p0.y; return x1*x2 + y1*y2; } function iprod1(p0, p1, p2, p3) { var x1, y1, x2, y2; x1 = p1.x - p0.x; y1 = p1.y - p0.y; x2 = p3.x - p2.x; y2 = p3.y - p2.y; return x1 * x2 + y1 * y2; } function ddist(p, q) { return Math.sqrt((p.x - q.x) * (p.x - q.x) + (p.y - q.y) * (p.y - q.y)); } module.exports = { luminance: function (r, g, b) { return Math.round(0.2126 * r + 0.7153 * g + 0.0721 * b); }, between: function(val, min, max) { return val >= min && val <= max; }, clamp: function(val, min, max) { return Math.min(max, Math.max(min, val)); }, isNumber: function(val) { return typeof val === 'number'; }, setHtmlAttr: setHtmlAttribute, /** * Generates path instructions for given curve * * @param {Curve} curve * @param {Number} [scale] * @returns {string} */ renderCurve: function(curve, scale) { scale = scale || 1; var startingPoint = curve.c[(curve.n - 1) * 3 + 2]; var path = 'M ' + fixed(startingPoint.x * scale) + ' ' + fixed(startingPoint.y * scale) + ' '; curve.tag.forEach(function(tag, i) { var i3 = i * 3; var p0 = curve.c[i3]; var p1 = curve.c[i3 + 1]; var p2 = curve.c[i3 + 2]; if (tag === "CURVE") { path += 'C '; path += fixed(p0.x * scale) + ' ' + fixed(p0.y * scale) + ', '; path += fixed(p1.x * scale) + ' ' + fixed(p1.y * scale) + ', '; path += fixed(p2.x * scale) + ' ' + fixed(p2.y * scale) + ' '; } else if (tag === "CORNER") { path += 'L '; path += fixed(p1.x * scale) + ' ' + fixed(p1.y * scale) + ' '; path += fixed(p2.x * scale) + ' ' + fixed(p2.y * scale) + ' '; } }); return path; }, bezier: function bezier(t, p0, p1, p2, p3) { var s = 1 - t, res = new Point(); res.x = s*s*s*p0.x + 3*(s*s*t)*p1.x + 3*(t*t*s)*p2.x + t*t*t*p3.x; res.y = s*s*s*p0.y + 3*(s*s*t)*p1.y + 3*(t*t*s)*p2.y + t*t*t*p3.y; return res; }, tangent: function tangent(p0, p1, p2, p3, q0, q1) { var A, B, C, a, b, c, d, s, r1, r2; A = cprod(p0, p1, q0, q1); B = cprod(p1, p2, q0, q1); C = cprod(p2, p3, q0, q1); a = A - 2 * B + C; b = -2 * A + 2 * B; c = A; d = b * b - 4 * a * c; if (a===0 || d<0) { return -1.0; } s = Math.sqrt(d); r1 = (-b + s) / (2 * a); r2 = (-b - s) / (2 * a); if (r1 >= 0 && r1 <= 1) { return r1; } else if (r2 >= 0 && r2 <= 1) { return r2; } else { return -1.0; } }, mod: mod, xprod: xprod, cyclic: cyclic, sign: sign, quadform: quadform, interval: interval, dorth_infty: dorth_infty, ddenom: ddenom, dpara: dpara, cprod: cprod, iprod: iprod, iprod1: iprod1, ddist: ddist }; ================================================ FILE: package.json ================================================ { "name": "potrace", "version": "2.1.2", "description": "Potrace in Javascript, for NodeJS", "main": "lib/index.js", "scripts": { "test": "cd test && mocha test.js --reporter spec" }, "repository": { "type": "git", "url": "git+https://github.com/tooolbox/node-potrace.git" }, "keywords": [ "potrace", "trace", "tracing", "svg", "bitmap", "posterization" ], "author": "mattmc", "license": "GPL-2.0", "bugs": { "url": "https://github.com/tooolbox/node-potrace/issues" }, "homepage": "https://github.com/tooolbox/node-potrace#readme", "dependencies": { "jimp": "^0.6.4" }, "devDependencies": { "lodash": "^4.15.0", "mocha": "^3.0.2", "should": "^11.1.0", "should-sinon": "0.0.5", "sinon": "^1.17.5" } } ================================================ FILE: test/test.js ================================================ 'use strict'; var _ = require('lodash'), assert = require('assert'), should = require('should'), sinon = require('sinon'); require('should-sinon'); var fs = require('fs'), Jimp = require('jimp'), Potrace = require('../lib/Potrace'), Posterizer = require('../lib/Posterizer'), Histogram = require('../lib/types/Histogram'), lib = require('../lib/index'); var PATH_TO_YAO = './sources/yao.jpg'; var PATH_TO_LENNA = './sources/Lenna.png'; var PATH_TO_BLACK_AND_WHITE_IMAGE = './sources/clouds.jpg'; var blackImage = new Jimp(100, 100, 0x000000FF); var whiteImage = new Jimp(100, 100, 0xFFFFFFFF); describe('Histogram class (private, responsible for auto thresholding)', function() { var histogram = null; var blackHistogram = new Histogram(blackImage, Histogram.MODE_LUMINANCE); var whiteHistogram = new Histogram(whiteImage, Histogram.MODE_LUMINANCE); before(function(done) { this.timeout(10000); Jimp.read(PATH_TO_LENNA, function(err, img) { if (err) throw err; histogram = new Histogram(img, Histogram.MODE_LUMINANCE); done(); }); }); describe('#getDominantColor', function() { it('gives different results with different tolerance values', function() { assert.equal(histogram.getDominantColor(0, 255), 149); assert.equal(histogram.getDominantColor(0, 255, 10), 143); }); it('has default argument values of 0, 255 and 1', function() { assert.equal(histogram.getDominantColor(), histogram.getDominantColor(0, 255, 1)); }); it('works for a segment of histogram', function() { assert.equal(41, histogram.getDominantColor(20, 80)); }); it('does not fail when min and max values are the same', function() { assert.equal(histogram.getDominantColor(42, 42), 42); }); it('returns -1 if colors from the range are not present on image', function() { assert.equal(histogram.getDominantColor(0, 15), -1); assert.equal(histogram.getDominantColor(7, 7, 1), -1); }); it('throws error if range start is larger than range end', function() { (function() { histogram.getDominantColor(80, 20); }).should.throw(); }); it('behaves predictably in edge cases', function() { blackHistogram.getDominantColor(0, 255).should.be.equal(0); whiteHistogram.getDominantColor(0, 255).should.be.equal(255); whiteHistogram.getDominantColor(25, 235).should.be.equal(-1); // Tolerance should not affect returned value blackHistogram.getDominantColor(0, 255, 15).should.be.equal(0); whiteHistogram.getDominantColor(0, 255, 15).should.be.equal(255); }) }); describe('#getStats', function() { function toFixedDeep(stats, fractionalDigits) { return _.cloneDeepWith(stats, function(val) { if (_.isNumber(val) && !_.isInteger(val)) { return parseFloat(val.toFixed(fractionalDigits)); } }); } it('produces expected stats object for entire histogram', function() { var expectedValue = { levels: { mean: 116.7673568725586, median: 95, stdDev: 49.42205692905339, unique: 222 }, pixelsPerLevel: { mean: 1028.0156862745098, median: 1180.8288288288288, peak: 2495 }, pixels: 262144 }; assert.deepEqual( toFixedDeep(histogram.getStats(), 4), toFixedDeep(expectedValue, 4) ); }); it('produces expected stats object for histogram segment', function() { var expectedValue = { levels: { mean: 121.89677761754915, median: 93, stdDev: 30.2466970087377, unique: 121 }, pixelsPerLevel: { mean: 1554.4916666666666, median: 1541.6446280991736, peak: 2495 }, pixels: 186539 }; assert.deepEqual( toFixedDeep(histogram.getStats(60, 180), 4), toFixedDeep(expectedValue, 4) ); }); it('throws error if range start is larger than range end', function() { (function() { histogram.getStats(255, 123); }).should.throw(); }); it('behaves predictably in edge cases', function() { var blackImageStats = blackHistogram.getStats(); var whiteImageStats = blackHistogram.getStats(); blackImageStats.levels.mean.should.be.equal(blackImageStats.levels.median); whiteImageStats.levels.mean.should.be.equal(whiteImageStats.levels.median); blackHistogram.getStats(25, 235).should.be.deepEqual(whiteHistogram.getStats(25, 235)); }); }); describe('#multilevelThresholding', function() { it('calculates correct thresholds', function() { assert.deepEqual(histogram.multilevelThresholding(1), [111]); assert.deepEqual(histogram.multilevelThresholding(2), [ 92, 154 ]); assert.deepEqual(histogram.multilevelThresholding(3), [ 73, 121, 168 ]); }); it('works for histogram segment', function() { assert.deepEqual(histogram.multilevelThresholding(2, 60, 180), [ 103, 138 ]); }); it('calculates as many thresholds as can be fit in given range', function() { assert.deepEqual(histogram.multilevelThresholding(2, 102, 106), [ 103, 104 ]); assert.deepEqual(histogram.multilevelThresholding(2, 103, 106), [ 104 ]); }); it('returns empty array if no colors from histogram segment is present on the image', function() { assert.deepEqual(histogram.multilevelThresholding(3, 2, 14), []); }); it('throws error if range start is larger than range end', function() { (function() { histogram.multilevelThresholding(2, 180, 60); }).should.throw(); }); }); }); describe('Potrace class', function() { var jimpInstance = null; this.timeout(10000); before(function(done) { Jimp.read(PATH_TO_YAO, function(err, img) { if (err) { return done(err); } jimpInstance = img; done(); }); }); describe('#loadImage', function() { it('instance is being passed to callback function as context', function(done) { var instance = new Potrace(); instance.loadImage(PATH_TO_YAO, function(err) { this.should.be.an.instanceOf(Potrace).and.be.equal(instance); done(err); }); }); it('supports Jimp instances provided as source image', function(done) { var instance = new Potrace(); instance.loadImage(jimpInstance, done); }); it('should throw error if called before previous image was loaded', function(done) { function onImageLoad() { if (firstFinished && secondFinished) { done(); } } var potraceInstance = new Potrace(); var firstFinished = false; var secondFinished = false; potraceInstance.loadImage(PATH_TO_LENNA, function(err) { firstFinished = true; should(function() { should.ifError(err); }).throw(/another.*instead/i); onImageLoad(); }); potraceInstance.loadImage(PATH_TO_YAO, function(err) { secondFinished = true; should(function() { should.ifError(err); }).not.throw(); onImageLoad(); }); }); }); describe('#_processPath', function() { var instance = new Potrace(); var processingSpy = null; before(function() { processingSpy = instance._processPath = sinon.spy(Potrace.prototype._processPath); }); it('should not execute until path is requested for the first time', function(done) { instance.loadImage(jimpInstance, function() { processingSpy.should.have.callCount(0); this.getSVG(); processingSpy.should.have.callCount(1); done(); }); }); it('should not execute on repetitive SVG/Symbol export', function() { instance.loadImage(jimpInstance, function() { var initialCallCount = processingSpy.callCount; this.getSVG(); this.getSVG(); this.getPathTag(); this.getPathTag('red'); this.getSymbol('symbol-id'); processingSpy.should.have.callCount(initialCallCount); }); }); it('should not execute after change of foreground/background colors', function() { instance.loadImage(jimpInstance, function() { var initialCallCount = processingSpy.callCount; this.setParameters({ color: 'red' }); this.getSVG(); this.setParameters({ background: 'crimson' }); this.getSVG(); processingSpy.should.have.callCount(initialCallCount); }); }); }); describe('#getSVG', function() { var instanceYao = new Potrace(); before(function(done) { instanceYao.loadImage(jimpInstance, done); }); it('produces expected results with different thresholds', function() { var expected; expected = fs.readFileSync('./reference-copies/potrace-bw-threshold-128.svg', { encoding: 'utf8' }); instanceYao.setParameters({ threshold: 128 }); assert.equal(instanceYao.getSVG(), expected, 'Image with threshold 128 does not match with reference copy'); expected = fs.readFileSync('./reference-copies/potrace-bw-threshold-65.svg', { encoding: 'utf8' }); instanceYao.setParameters({ threshold: 65 }); assert.equal(instanceYao.getSVG(), expected, 'Image with threshold 65 does not match with reference copy'); expected = fs.readFileSync('./reference-copies/potrace-bw-threshold-170.svg', { encoding: 'utf8' }); instanceYao.setParameters({ threshold: 170 }); assert.equal(instanceYao.getSVG(), expected, 'Image with threshold 170 does not match with reference copy'); }); it('produces expected white on black image with threshold 170', function(done) { var instance = new Potrace({ threshold: 128, blackOnWhite: false, color: 'cyan', background: 'darkred' }); instance.loadImage(PATH_TO_BLACK_AND_WHITE_IMAGE, function(err) { if (err) return done(err); var expected = fs.readFileSync('./reference-copies/potrace-wb-threshold-128.svg', { encoding: 'utf8' }); var actual = instance.getSVG(); assert.equal(actual, expected); done(); }); }); }); describe('#getSymbol', function() { var instanceYao = new Potrace(); before(function(done) { instanceYao.loadImage(jimpInstance, done); }); it('should not have fill color or background', function() { instanceYao.setParameters({ color: 'red', background: 'cyan' }); var symbol = instanceYao.getSymbol('whatever'); symbol.should.not.match(/]+(?:fill="\s*"|fill='\s*'|)[^>]*>/i); }); }); describe('behaves predictably in edge cases', function() { var instance = new Potrace(); var bwBlackThreshold0; var bwBlackThreshold255; var bwWhiteThreshold0; var bwWhiteThreshold255; var wbWhiteThreshold0; var wbWhiteThreshold255; var wbBlackThreshold0; var wbBlackThreshold255; before(function() { bwBlackThreshold0 = fs.readFileSync('./reference-copies/potrace-bw-black-threshold-0.svg', { encoding: 'utf8' }); bwBlackThreshold255 = fs.readFileSync('./reference-copies/potrace-bw-black-threshold-255.svg', { encoding: 'utf8' }); bwWhiteThreshold0 = fs.readFileSync('./reference-copies/potrace-bw-white-threshold-0.svg', { encoding: 'utf8' }); bwWhiteThreshold255 = fs.readFileSync('./reference-copies/potrace-bw-white-threshold-255.svg', { encoding: 'utf8' }); wbWhiteThreshold0 = fs.readFileSync('./reference-copies/potrace-wb-white-threshold-0.svg', { encoding: 'utf8' }); wbWhiteThreshold255 = fs.readFileSync('./reference-copies/potrace-wb-white-threshold-255.svg', { encoding: 'utf8' }); wbBlackThreshold0 = fs.readFileSync('./reference-copies/potrace-wb-black-threshold-0.svg', { encoding: 'utf8' }); wbBlackThreshold255 = fs.readFileSync('./reference-copies/potrace-wb-black-threshold-255.svg', { encoding: 'utf8' }); }); it('compares colors against threshold in the same way as original tool', function(done) { instance.loadImage(blackImage, function(err) { if (err) { return done(err); } instance.setParameters({ blackOnWhite: true, threshold: 0 }); instance.getSVG().should.be.equal(bwBlackThreshold0); instance.setParameters({ blackOnWhite: true, threshold: 255 }); instance.getSVG().should.be.equal(bwBlackThreshold255); instance.loadImage(whiteImage, function() { if (err) { return done(err); } instance.setParameters({ blackOnWhite: true, threshold: 0 }); instance.getSVG().should.be.equal(bwWhiteThreshold0); instance.setParameters({ blackOnWhite: true, threshold: 255 }); instance.getSVG().should.be.equal(bwWhiteThreshold255); done(); }); }); }); it('acts in the same way when colors are inverted', function(done) { instance.loadImage(whiteImage, function(err) { if (err) { return done(err); } instance.setParameters({ blackOnWhite: false, threshold: 255 }); instance.getSVG().should.be.equal(wbWhiteThreshold255); instance.setParameters({ blackOnWhite: false, threshold: 0 }); instance.getSVG().should.be.equal(wbWhiteThreshold0); instance.loadImage(blackImage, function() { if (err) { return done(err); } instance.setParameters({ blackOnWhite: false, threshold: 255 }); instance.getSVG().should.be.equal(wbBlackThreshold255); instance.setParameters({ blackOnWhite: false, threshold: 0 }); instance.getSVG().should.be.equal(wbBlackThreshold0); done(); }); }); }); }); }); describe('Posterizer class', function() { var jimpInstance = null; var sharedPosterizerInstance = new Posterizer(); this.timeout(10000); before(function(done) { Jimp.read(PATH_TO_YAO, function(err, img) { if (err) { return done(err); } jimpInstance = img; done(); }); }); describe('#_getRanges', function() { var posterizer = new Posterizer(); function getColorStops() { return posterizer._getRanges().map(function(item) { return item.value; }); } before(function(done) { posterizer.loadImage(PATH_TO_YAO, done); }); it('returns correctly calculated color stops with "equally spread" distribution', function() { posterizer.setParameters({ rangeDistribution: Posterizer.RANGES_EQUAL, threshold: 200, steps: 4, blackOnWhite: true }); getColorStops().should.be.deepEqual([200, 150, 100, 50]); posterizer.setParameters({ rangeDistribution: Posterizer.RANGES_EQUAL, threshold: 155, steps: 4, blackOnWhite: false }); getColorStops().should.be.deepEqual([155, 180, 205, 230]); posterizer.setParameters({ rangeDistribution: Posterizer.RANGES_EQUAL, threshold: Potrace.THRESHOLD_AUTO, steps: 4, blackOnWhite: true }); getColorStops().should.be.deepEqual([206, 154.5, 103, 51.5]); }); it('returns correctly calculated color stops with "auto" distribution', function() { posterizer.setParameters({ rangeDistribution: Posterizer.RANGES_AUTO, threshold: Potrace.THRESHOLD_AUTO, steps: 3, blackOnWhite: true }); getColorStops().should.be.deepEqual([219, 156, 71]); posterizer.setParameters({ rangeDistribution: Posterizer.RANGES_AUTO, threshold: Potrace.THRESHOLD_AUTO, steps: 3, blackOnWhite: false }); getColorStops().should.be.deepEqual([71, 156, 219]); // Now with predefined threshold posterizer.setParameters({ rangeDistribution: Posterizer.RANGES_AUTO, threshold: 128, steps: 4, blackOnWhite: true }); getColorStops().should.be.deepEqual([128, 97, 62, 24]); posterizer.setParameters({ rangeDistribution: Posterizer.RANGES_AUTO, threshold: 128, steps: 4, blackOnWhite: false }); getColorStops().should.be.deepEqual([128, 166, 203, 237]); }); it('correctly handles predefined array of color stops', function() { posterizer.setParameters({ steps: [20, 60, 80, 160], threshold: 120, blackOnWhite: true }); getColorStops().should.be.deepEqual([160, 80, 60, 20]); posterizer.setParameters({ steps: [20, 60, 80, 160], threshold: 180, blackOnWhite: true }); getColorStops().should.be.deepEqual([180, 160, 80, 60, 20]); posterizer.setParameters({ steps: [20, 60, 80, 160], threshold: 180, blackOnWhite: false }); getColorStops().should.be.deepEqual([20, 60, 80, 160, 180]); posterizer.setParameters({ steps: [212, 16, 26, 50, 212, 128, 211], threshold: 180, blackOnWhite: false }); getColorStops().should.be.deepEqual([16, 26, 50, 128, 211, 212], 'Duplicated items should be present only once'); posterizer.setParameters({ steps: [15, 42, 200, 460, 0, -10], threshold: 180, blackOnWhite: false }); getColorStops().should.be.deepEqual([0, 15, 42, 200], 'Values out of range should be ignored'); }); }); describe('#loadImage', function() { it('instance is being passed to callback function as context', function(done) { sharedPosterizerInstance.loadImage(PATH_TO_YAO, function(err) { this.should.be.an.instanceOf(Posterizer).and.be.equal(sharedPosterizerInstance); done(err); }); }); }); describe('#getSVG', function() { var instanceYao = sharedPosterizerInstance; it('produces expected results with different thresholds', function() { var expected; instanceYao.setParameters({ threshold: 128 }); expected = fs.readFileSync('./reference-copies/posterized-yao-black-threshold-128.svg', { encoding: 'utf8' }); assert.equal(instanceYao.getSVG(), expected, 'Image with threshold 128 does not match with reference copy'); instanceYao.setParameters({ threshold: 65 }); expected = fs.readFileSync('./reference-copies/posterized-yao-black-threshold-65.svg', { encoding: 'utf8' }); assert.equal(instanceYao.getSVG(), expected, 'Image with threshold 65 does not match with reference copy'); instanceYao.setParameters({ threshold: 170 }); expected = fs.readFileSync('./reference-copies/posterized-yao-black-threshold-170.svg', { encoding: 'utf8' }); assert.equal(instanceYao.getSVG(), expected, 'Image with threshold 170 does not match with reference copy'); }); it('produces expected white on black image with threshold 170', function(done) { var instance = new Posterizer({ threshold: 40, blackOnWhite: false, steps: 3, color: 'beige', background: '#222' }); instance.loadImage('sources/clouds.jpg', function(err) { if (err) return done(err); var expected = fs.readFileSync('./reference-copies/posterized-clouds-white-40.svg', { encoding: 'utf8' }); var actual = instance.getSVG(); assert.equal(actual, expected); done(); }); }); }); describe('#getSymbol', function() { var instanceYao = new Posterizer(); before(function(done) { instanceYao.loadImage(jimpInstance, done); }); it('should not have fill color or background', function() { instanceYao.setParameters({ color: 'red', background: 'cyan', steps: 3 }); var symbol = instanceYao.getSymbol('whatever'); symbol.should.not.match(/]+(?:fill="\s*"|fill='\s*'|)[^>]*>/i); }); }); describe('edge cases', function() { var instance = new Posterizer(); it('does not break on images filled with one color', function(done) { instance.loadImage(blackImage, function(err) { if (err) { return done(err); } // black image should give us one black layer... instance.setParameters({ blackOnWhite: true, threshold: 128 }); instance.getSVG().should.match(/