├── .github ├── FUNDING.yml └── workflows │ └── ci.yml ├── .gitignore ├── .gitmodules ├── CHANGELOG ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── COPYRIGHT ├── Cargo.toml ├── INSTALL ├── README.md ├── pngquant.1 ├── pngquant.c ├── pngquant.xcodeproj └── project.pbxproj ├── pngquant_opts.c ├── pngquant_opts.h ├── rust ├── bin.rs ├── build.rs ├── ffi.rs └── rwpng_cocoa.rs ├── rwpng.c ├── rwpng.h ├── snapcraft.yaml └── test ├── fuzzer.c ├── img ├── metadata.png └── test.png ├── test.c └── test.sh /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: [kornelski] 2 | liberapay: [kornel] 3 | custom: ['https://paypal.me/kornel'] 4 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | env: 4 | CARGO_REGISTRIES_CRATES_IO_PROTOCOL: sparse 5 | CARGO_TERM_COLOR: always 6 | 7 | on: 8 | push: 9 | branches: [ main ] 10 | pull_request: 11 | branches: [ main ] 12 | 13 | jobs: 14 | build: 15 | 16 | runs-on: ubuntu-latest 17 | 18 | steps: 19 | - uses: actions/checkout@v2 20 | with: 21 | submodules: true 22 | - uses: actions-rs/toolchain@v1 23 | with: 24 | toolchain: stable 25 | - uses: actions-rs/cargo@v1 26 | with: 27 | command: test 28 | args: --all 29 | 30 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.dylib 2 | *.mode1v3 3 | *.o 4 | *.lo 5 | *.pbxuser 6 | build 7 | DerivedData 8 | pngquant 9 | lib/libimagequant.a 10 | *.obj 11 | *.lib 12 | config.mk 13 | test/test 14 | target/ 15 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "lib"] 2 | path = lib 3 | url = ../../ImageOptim/libimagequant.git 4 | -------------------------------------------------------------------------------- /CHANGELOG: -------------------------------------------------------------------------------- 1 | version 3.0 2 | ----------- 3 | - replaced C libimagequant library with a Rust imagequant crate 4 | - switched build system from make to Cargo 5 | 6 | version 2.17 7 | ------------ 8 | - fixed Unicode filenames on Windows 9 | - builds for ARM 10 | - small quality improvements 11 | 12 | version 2.16 13 | ------------ 14 | - reduced stack usage, prevenitng stack overlfow in pathological cases 15 | 16 | version 2.13-2.15 17 | ------------ 18 | - speed and quality improvements 19 | 20 | version 2.12 21 | ------------ 22 | - improved speed on large images 23 | - OpenMP fixes/workarounds 24 | 25 | version 2.11 26 | ------------ 27 | - fixed wildcard support on Windows 28 | - fixed argument parsing on Windows 29 | 30 | version 2.10 31 | ------------ 32 | - supports building with Rust/Cargo 33 | - supports dynamic linking with system-wide libimagequant 34 | 35 | version 2.9 36 | ----------- 37 | - added support for `-o -` 38 | - windows/JNI build fixes 39 | 40 | version 2.8 41 | ----------- 42 | - libimagequant is a separate project 43 | - --strip option to disable copying of PNG metadata 44 | 45 | version 2.7 46 | ----------- 47 | - improved dithering of saturated and semitransparent colors 48 | - fixed order of log output when using openmp 49 | - improved quality sanity check in --skip-if-larger option 50 | - disabled palette post-processing on colors from --map option to preserve them exactly 51 | 52 | version 2.6 53 | ----------- 54 | - when source image has no color profile information, the output won't have either 55 | 56 | version 2.5 57 | ----------- 58 | - replaced color search algorithm with vantage point tree, which is much faster and more reliable 59 | - deprecated IE6 workaround 60 | - warn when compiled without color profile support 61 | - Rust API for libimagequant 62 | 63 | version 2.4 64 | ----------- 65 | - fixed remapping of bright colors when dithering 66 | 67 | version 2.3 68 | ----------- 69 | - added ./configure script for better support of Intel C compiler and dependencies [thanks to pdknsk] 70 | - tweaked quality metric to better estimate quality of images with large solid backgrounds [thanks to Rolf Timmermans] 71 | - atomic file saves and fixed --skip-if-larger 72 | - avoid applying quality setting to images that use palette already 73 | - preserving standard PNG chunks (requires libpng 1.6) 74 | - deprecated libpng 1.2 support 75 | 76 | version 2.2 77 | ----------- 78 | - preserving of unknown PNG chunks (enables optimized Android 9-patch images) 79 | - improved color profile support: cHRM & gAMA as alternative to ICC profiles, OpenMP acceleration 80 | - improved support for Intel C Compiler, speedup in 32-bit GCC, and some workarounds for Visual Studio's incomplete C support 81 | 82 | version 2.1 83 | ----------- 84 | - option to save files only if they're compressed better than the original 85 | - option to generate posterized output (for use with 16-bit textures) 86 | - support for ICC profiles via Little CMS library 87 | 88 | version 2.0 89 | ----------- 90 | - refactored codebase into pngquant and standalone libimagequant 91 | - reduced memory usage by further 30% (and more for very large images) 92 | - less precise remapping improving speed by 25% in higher speed settings 93 | - --output option for writing converted file under the given path 94 | - light dithering with --floyd=0.5 95 | - fixed regression in dithering of alpha channel 96 | 97 | version 1.8 98 | ----------- 99 | - min/max quality option (number of colors is automatically adjusted for desired quality level) 100 | - switched option parsing to getopt_long (syntax such as -s1 and --ext=ext is supported) 101 | - significantly improved performance thanks to custom partial sorting 102 | - optional Cocoa (Mac OS X) image reader for color profile support 103 | - reduced memory usage by 20% 104 | - remapping improved for very low number of colors 105 | 106 | version 1.7 107 | ----------- 108 | - new, accurate RGBA color similarity algorithm 109 | - change of optional SSE3 code to SSE2 that is always enabled on x86-64 110 | - optional OpenMP-based parallelisation of remapping 111 | - changed long options to use double hyphen (-force to --force) [thanks to Jari Aalto] 112 | 113 | version 1.6 114 | ----------- 115 | - novel dithering algorithm that doesn't add noise unless necessary 116 | - perceptual weighting of colors taking into account edges and noise 117 | - much faster remapping 118 | - improved portability, makefiles and man page 119 | 120 | version 1.5 121 | ----------- 122 | - palettes postprocessed with Voronoi iteration 123 | - better RGBA color similarity algorithm and Floyd-Steinberg remapping 124 | - SSE optimisations 125 | 126 | version 1.4 127 | ----------- 128 | - median cut is applied many times in a feedback loop 129 | - speed/quality trade-off option 130 | - faster remap of transparent areas 131 | 132 | version 1.3 133 | ----------- 134 | - significant changes to the algorithm: use of variance 135 | to find largest dimensioin and to split most varying boxes 136 | - use of premultiplied alpha for color blending 137 | - conversion of output to gamma 2.2 138 | 139 | version 1.2 140 | ----------- 141 | - color computation done in floating point 142 | - gamma correction applied 143 | - dropped support for very old systems & compilers 144 | 145 | version 1.1 146 | ----------- 147 | - alpha-sensitive color reduction and dithering 148 | - support -- and - arguments in command line 149 | - number of colors optional (defaults to 256) 150 | - increased maximum number of colors in histogram 151 | 152 | version 1.0 153 | ----------- 154 | - cleaned up Makefile.unx (better gcc optimizations, "clean" target) 155 | - recompiled binaries with zlib 1.1.4 156 | 157 | version 0.95 158 | ------------ 159 | - fixed Win32 filter bug (binary mode for stdin/stdout) 160 | - fixed cosmetic "choosing colors" verbosity buglet 161 | - fixed palette-size bug when number of colors in image < number requested 162 | - fixed sample-depth bug (png_set_packing() not retroactively smart) 163 | 164 | version 0.91 165 | ------------ 166 | - fixed some verbose/non-verbose oopers 167 | - fixed Win32 (MSVC) portability issues (getpid(), random(), srandom()) 168 | - added Makefile.w32 for MSVC (tested with 5.0) 169 | 170 | version 0.90 171 | ------------ 172 | - added support for multiple files on command line 173 | - changed stdin support to write PNG stream to stdout (not "stdin-fs8.png") 174 | 175 | version 0.75 176 | ------------ 177 | - added support for any type of input file [Glenn Randers-Pehrson] 178 | - fixed palette-(re)scaling bug 179 | - added -verbose and -quiet options (default now is -quiet) 180 | - added palette-remapping to minimize size of tRNS chunk 181 | - made Floyd-Steinberg dithering default 182 | - changed output naming scheme to -fs8.png and -or8.png (FS or ordered dither) 183 | 184 | version 0.70 185 | ------------ 186 | - first public release 187 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, gender identity and expression, level of experience, 9 | nationality, personal appearance, race, religion, or sexual identity and 10 | orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at kornel@geekhood.net. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at [http://contributor-covenant.org/version/1/4][version] 72 | 73 | [homepage]: http://contributor-covenant.org 74 | [version]: http://contributor-covenant.org/version/1/4/ 75 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | 2 | Thank you for contributing! pngquant and libimagequant are licensed under multiple 3 | licensed, so to make things clear, I'm accepting contributions as licensed under 4 | the BSD 2-clause license: 5 | 6 | Redistribution and use in source and binary forms, with or without modification, 7 | are permitted provided that the following conditions are met: 8 | 9 | 1. Redistributions of source code must retain the above copyright notice, 10 | this list of conditions and the following disclaimer. 11 | 12 | 2. Redistributions in binary form must reproduce the above copyright notice, 13 | this list of conditions and the following disclaimer in the documentation 14 | and/or other materials provided with the distribution. 15 | 16 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 17 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 18 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 20 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 21 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 22 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 23 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 24 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 25 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | 27 | -------------------------------------------------------------------------------- /COPYRIGHT: -------------------------------------------------------------------------------- 1 | 2 | pngquant and libimagequant are derived from code by Jef Poskanzer and Greg Roelofs 3 | licensed under pngquant's original licenses (near the end of this file), 4 | and contain extensive changes and additions by Kornel Lesiński 5 | licensed under GPL v3 or later. 6 | 7 | - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 8 | 9 | pngquant © 2009-2018 by Kornel Lesiński. 10 | 11 | GNU GENERAL PUBLIC LICENSE 12 | Version 3, 29 June 2007 13 | 14 | Copyright (C) 2007 Free Software Foundation, Inc. 15 | Everyone is permitted to copy and distribute verbatim copies 16 | of this license document, but changing it is not allowed. 17 | 18 | Preamble 19 | 20 | The GNU General Public License is a free, copyleft license for 21 | software and other kinds of works. 22 | 23 | The licenses for most software and other practical works are designed 24 | to take away your freedom to share and change the works. By contrast, 25 | the GNU General Public License is intended to guarantee your freedom to 26 | share and change all versions of a program--to make sure it remains free 27 | software for all its users. We, the Free Software Foundation, use the 28 | GNU General Public License for most of our software; it applies also to 29 | any other work released this way by its authors. You can apply it to 30 | your programs, too. 31 | 32 | When we speak of free software, we are referring to freedom, not 33 | price. Our General Public Licenses are designed to make sure that you 34 | have the freedom to distribute copies of free software (and charge for 35 | them if you wish), that you receive source code or can get it if you 36 | want it, that you can change the software or use pieces of it in new 37 | free programs, and that you know you can do these things. 38 | 39 | To protect your rights, we need to prevent others from denying you 40 | these rights or asking you to surrender the rights. Therefore, you have 41 | certain responsibilities if you distribute copies of the software, or if 42 | you modify it: responsibilities to respect the freedom of others. 43 | 44 | For example, if you distribute copies of such a program, whether 45 | gratis or for a fee, you must pass on to the recipients the same 46 | freedoms that you received. You must make sure that they, too, receive 47 | or can get the source code. And you must show them these terms so they 48 | know their rights. 49 | 50 | Developers that use the GNU GPL protect your rights with two steps: 51 | (1) assert copyright on the software, and (2) offer you this License 52 | giving you legal permission to copy, distribute and/or modify it. 53 | 54 | For the developers' and authors' protection, the GPL clearly explains 55 | that there is no warranty for this free software. For both users' and 56 | authors' sake, the GPL requires that modified versions be marked as 57 | changed, so that their problems will not be attributed erroneously to 58 | authors of previous versions. 59 | 60 | Some devices are designed to deny users access to install or run 61 | modified versions of the software inside them, although the manufacturer 62 | can do so. This is fundamentally incompatible with the aim of 63 | protecting users' freedom to change the software. The systematic 64 | pattern of such abuse occurs in the area of products for individuals to 65 | use, which is precisely where it is most unacceptable. Therefore, we 66 | have designed this version of the GPL to prohibit the practice for those 67 | products. If such problems arise substantially in other domains, we 68 | stand ready to extend this provision to those domains in future versions 69 | of the GPL, as needed to protect the freedom of users. 70 | 71 | Finally, every program is threatened constantly by software patents. 72 | States should not allow patents to restrict development and use of 73 | software on general-purpose computers, but in those that do, we wish to 74 | avoid the special danger that patents applied to a free program could 75 | make it effectively proprietary. To prevent this, the GPL assures that 76 | patents cannot be used to render the program non-free. 77 | 78 | The precise terms and conditions for copying, distribution and 79 | modification follow. 80 | 81 | TERMS AND CONDITIONS 82 | 83 | 0. Definitions. 84 | 85 | "This License" refers to version 3 of the GNU General Public License. 86 | 87 | "Copyright" also means copyright-like laws that apply to other kinds of 88 | works, such as semiconductor masks. 89 | 90 | "The Program" refers to any copyrightable work licensed under this 91 | License. Each licensee is addressed as "you". "Licensees" and 92 | "recipients" may be individuals or organizations. 93 | 94 | To "modify" a work means to copy from or adapt all or part of the work 95 | in a fashion requiring copyright permission, other than the making of an 96 | exact copy. The resulting work is called a "modified version" of the 97 | earlier work or a work "based on" the earlier work. 98 | 99 | A "covered work" means either the unmodified Program or a work based 100 | on the Program. 101 | 102 | To "propagate" a work means to do anything with it that, without 103 | permission, would make you directly or secondarily liable for 104 | infringement under applicable copyright law, except executing it on a 105 | computer or modifying a private copy. Propagation includes copying, 106 | distribution (with or without modification), making available to the 107 | public, and in some countries other activities as well. 108 | 109 | To "convey" a work means any kind of propagation that enables other 110 | parties to make or receive copies. Mere interaction with a user through 111 | a computer network, with no transfer of a copy, is not conveying. 112 | 113 | An interactive user interface displays "Appropriate Legal Notices" 114 | to the extent that it includes a convenient and prominently visible 115 | feature that (1) displays an appropriate copyright notice, and (2) 116 | tells the user that there is no warranty for the work (except to the 117 | extent that warranties are provided), that licensees may convey the 118 | work under this License, and how to view a copy of this License. If 119 | the interface presents a list of user commands or options, such as a 120 | menu, a prominent item in the list meets this criterion. 121 | 122 | 1. Source Code. 123 | 124 | The "source code" for a work means the preferred form of the work 125 | for making modifications to it. "Object code" means any non-source 126 | form of a work. 127 | 128 | A "Standard Interface" means an interface that either is an official 129 | standard defined by a recognized standards body, or, in the case of 130 | interfaces specified for a particular programming language, one that 131 | is widely used among developers working in that language. 132 | 133 | The "System Libraries" of an executable work include anything, other 134 | than the work as a whole, that (a) is included in the normal form of 135 | packaging a Major Component, but which is not part of that Major 136 | Component, and (b) serves only to enable use of the work with that 137 | Major Component, or to implement a Standard Interface for which an 138 | implementation is available to the public in source code form. A 139 | "Major Component", in this context, means a major essential component 140 | (kernel, window system, and so on) of the specific operating system 141 | (if any) on which the executable work runs, or a compiler used to 142 | produce the work, or an object code interpreter used to run it. 143 | 144 | The "Corresponding Source" for a work in object code form means all 145 | the source code needed to generate, install, and (for an executable 146 | work) run the object code and to modify the work, including scripts to 147 | control those activities. However, it does not include the work's 148 | System Libraries, or general-purpose tools or generally available free 149 | programs which are used unmodified in performing those activities but 150 | which are not part of the work. For example, Corresponding Source 151 | includes interface definition files associated with source files for 152 | the work, and the source code for shared libraries and dynamically 153 | linked subprograms that the work is specifically designed to require, 154 | such as by intimate data communication or control flow between those 155 | subprograms and other parts of the work. 156 | 157 | The Corresponding Source need not include anything that users 158 | can regenerate automatically from other parts of the Corresponding 159 | Source. 160 | 161 | The Corresponding Source for a work in source code form is that 162 | same work. 163 | 164 | 2. Basic Permissions. 165 | 166 | All rights granted under this License are granted for the term of 167 | copyright on the Program, and are irrevocable provided the stated 168 | conditions are met. This License explicitly affirms your unlimited 169 | permission to run the unmodified Program. The output from running a 170 | covered work is covered by this License only if the output, given its 171 | content, constitutes a covered work. This License acknowledges your 172 | rights of fair use or other equivalent, as provided by copyright law. 173 | 174 | You may make, run and propagate covered works that you do not 175 | convey, without conditions so long as your license otherwise remains 176 | in force. You may convey covered works to others for the sole purpose 177 | of having them make modifications exclusively for you, or provide you 178 | with facilities for running those works, provided that you comply with 179 | the terms of this License in conveying all material for which you do 180 | not control copyright. Those thus making or running the covered works 181 | for you must do so exclusively on your behalf, under your direction 182 | and control, on terms that prohibit them from making any copies of 183 | your copyrighted material outside their relationship with you. 184 | 185 | Conveying under any other circumstances is permitted solely under 186 | the conditions stated below. Sublicensing is not allowed; section 10 187 | makes it unnecessary. 188 | 189 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 190 | 191 | No covered work shall be deemed part of an effective technological 192 | measure under any applicable law fulfilling obligations under article 193 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 194 | similar laws prohibiting or restricting circumvention of such 195 | measures. 196 | 197 | When you convey a covered work, you waive any legal power to forbid 198 | circumvention of technological measures to the extent such circumvention 199 | is effected by exercising rights under this License with respect to 200 | the covered work, and you disclaim any intention to limit operation or 201 | modification of the work as a means of enforcing, against the work's 202 | users, your or third parties' legal rights to forbid circumvention of 203 | technological measures. 204 | 205 | 4. Conveying Verbatim Copies. 206 | 207 | You may convey verbatim copies of the Program's source code as you 208 | receive it, in any medium, provided that you conspicuously and 209 | appropriately publish on each copy an appropriate copyright notice; 210 | keep intact all notices stating that this License and any 211 | non-permissive terms added in accord with section 7 apply to the code; 212 | keep intact all notices of the absence of any warranty; and give all 213 | recipients a copy of this License along with the Program. 214 | 215 | You may charge any price or no price for each copy that you convey, 216 | and you may offer support or warranty protection for a fee. 217 | 218 | 5. Conveying Modified Source Versions. 219 | 220 | You may convey a work based on the Program, or the modifications to 221 | produce it from the Program, in the form of source code under the 222 | terms of section 4, provided that you also meet all of these conditions: 223 | 224 | a) The work must carry prominent notices stating that you modified 225 | it, and giving a relevant date. 226 | 227 | b) The work must carry prominent notices stating that it is 228 | released under this License and any conditions added under section 229 | 7. This requirement modifies the requirement in section 4 to 230 | "keep intact all notices". 231 | 232 | c) You must license the entire work, as a whole, under this 233 | License to anyone who comes into possession of a copy. This 234 | License will therefore apply, along with any applicable section 7 235 | additional terms, to the whole of the work, and all its parts, 236 | regardless of how they are packaged. This License gives no 237 | permission to license the work in any other way, but it does not 238 | invalidate such permission if you have separately received it. 239 | 240 | d) If the work has interactive user interfaces, each must display 241 | Appropriate Legal Notices; however, if the Program has interactive 242 | interfaces that do not display Appropriate Legal Notices, your 243 | work need not make them do so. 244 | 245 | A compilation of a covered work with other separate and independent 246 | works, which are not by their nature extensions of the covered work, 247 | and which are not combined with it such as to form a larger program, 248 | in or on a volume of a storage or distribution medium, is called an 249 | "aggregate" if the compilation and its resulting copyright are not 250 | used to limit the access or legal rights of the compilation's users 251 | beyond what the individual works permit. Inclusion of a covered work 252 | in an aggregate does not cause this License to apply to the other 253 | parts of the aggregate. 254 | 255 | 6. Conveying Non-Source Forms. 256 | 257 | You may convey a covered work in object code form under the terms 258 | of sections 4 and 5, provided that you also convey the 259 | machine-readable Corresponding Source under the terms of this License, 260 | in one of these ways: 261 | 262 | a) Convey the object code in, or embodied in, a physical product 263 | (including a physical distribution medium), accompanied by the 264 | Corresponding Source fixed on a durable physical medium 265 | customarily used for software interchange. 266 | 267 | b) Convey the object code in, or embodied in, a physical product 268 | (including a physical distribution medium), accompanied by a 269 | written offer, valid for at least three years and valid for as 270 | long as you offer spare parts or customer support for that product 271 | model, to give anyone who possesses the object code either (1) a 272 | copy of the Corresponding Source for all the software in the 273 | product that is covered by this License, on a durable physical 274 | medium customarily used for software interchange, for a price no 275 | more than your reasonable cost of physically performing this 276 | conveying of source, or (2) access to copy the 277 | Corresponding Source from a network server at no charge. 278 | 279 | c) Convey individual copies of the object code with a copy of the 280 | written offer to provide the Corresponding Source. This 281 | alternative is allowed only occasionally and noncommercially, and 282 | only if you received the object code with such an offer, in accord 283 | with subsection 6b. 284 | 285 | d) Convey the object code by offering access from a designated 286 | place (gratis or for a charge), and offer equivalent access to the 287 | Corresponding Source in the same way through the same place at no 288 | further charge. You need not require recipients to copy the 289 | Corresponding Source along with the object code. If the place to 290 | copy the object code is a network server, the Corresponding Source 291 | may be on a different server (operated by you or a third party) 292 | that supports equivalent copying facilities, provided you maintain 293 | clear directions next to the object code saying where to find the 294 | Corresponding Source. Regardless of what server hosts the 295 | Corresponding Source, you remain obligated to ensure that it is 296 | available for as long as needed to satisfy these requirements. 297 | 298 | e) Convey the object code using peer-to-peer transmission, provided 299 | you inform other peers where the object code and Corresponding 300 | Source of the work are being offered to the general public at no 301 | charge under subsection 6d. 302 | 303 | A separable portion of the object code, whose source code is excluded 304 | from the Corresponding Source as a System Library, need not be 305 | included in conveying the object code work. 306 | 307 | A "User Product" is either (1) a "consumer product", which means any 308 | tangible personal property which is normally used for personal, family, 309 | or household purposes, or (2) anything designed or sold for incorporation 310 | into a dwelling. In determining whether a product is a consumer product, 311 | doubtful cases shall be resolved in favor of coverage. For a particular 312 | product received by a particular user, "normally used" refers to a 313 | typical or common use of that class of product, regardless of the status 314 | of the particular user or of the way in which the particular user 315 | actually uses, or expects or is expected to use, the product. A product 316 | is a consumer product regardless of whether the product has substantial 317 | commercial, industrial or non-consumer uses, unless such uses represent 318 | the only significant mode of use of the product. 319 | 320 | "Installation Information" for a User Product means any methods, 321 | procedures, authorization keys, or other information required to install 322 | and execute modified versions of a covered work in that User Product from 323 | a modified version of its Corresponding Source. The information must 324 | suffice to ensure that the continued functioning of the modified object 325 | code is in no case prevented or interfered with solely because 326 | modification has been made. 327 | 328 | If you convey an object code work under this section in, or with, or 329 | specifically for use in, a User Product, and the conveying occurs as 330 | part of a transaction in which the right of possession and use of the 331 | User Product is transferred to the recipient in perpetuity or for a 332 | fixed term (regardless of how the transaction is characterized), the 333 | Corresponding Source conveyed under this section must be accompanied 334 | by the Installation Information. But this requirement does not apply 335 | if neither you nor any third party retains the ability to install 336 | modified object code on the User Product (for example, the work has 337 | been installed in ROM). 338 | 339 | The requirement to provide Installation Information does not include a 340 | requirement to continue to provide support service, warranty, or updates 341 | for a work that has been modified or installed by the recipient, or for 342 | the User Product in which it has been modified or installed. Access to a 343 | network may be denied when the modification itself materially and 344 | adversely affects the operation of the network or violates the rules and 345 | protocols for communication across the network. 346 | 347 | Corresponding Source conveyed, and Installation Information provided, 348 | in accord with this section must be in a format that is publicly 349 | documented (and with an implementation available to the public in 350 | source code form), and must require no special password or key for 351 | unpacking, reading or copying. 352 | 353 | 7. Additional Terms. 354 | 355 | "Additional permissions" are terms that supplement the terms of this 356 | License by making exceptions from one or more of its conditions. 357 | Additional permissions that are applicable to the entire Program shall 358 | be treated as though they were included in this License, to the extent 359 | that they are valid under applicable law. If additional permissions 360 | apply only to part of the Program, that part may be used separately 361 | under those permissions, but the entire Program remains governed by 362 | this License without regard to the additional permissions. 363 | 364 | When you convey a copy of a covered work, you may at your option 365 | remove any additional permissions from that copy, or from any part of 366 | it. (Additional permissions may be written to require their own 367 | removal in certain cases when you modify the work.) You may place 368 | additional permissions on material, added by you to a covered work, 369 | for which you have or can give appropriate copyright permission. 370 | 371 | Notwithstanding any other provision of this License, for material you 372 | add to a covered work, you may (if authorized by the copyright holders of 373 | that material) supplement the terms of this License with terms: 374 | 375 | a) Disclaiming warranty or limiting liability differently from the 376 | terms of sections 15 and 16 of this License; or 377 | 378 | b) Requiring preservation of specified reasonable legal notices or 379 | author attributions in that material or in the Appropriate Legal 380 | Notices displayed by works containing it; or 381 | 382 | c) Prohibiting misrepresentation of the origin of that material, or 383 | requiring that modified versions of such material be marked in 384 | reasonable ways as different from the original version; or 385 | 386 | d) Limiting the use for publicity purposes of names of licensors or 387 | authors of the material; or 388 | 389 | e) Declining to grant rights under trademark law for use of some 390 | trade names, trademarks, or service marks; or 391 | 392 | f) Requiring indemnification of licensors and authors of that 393 | material by anyone who conveys the material (or modified versions of 394 | it) with contractual assumptions of liability to the recipient, for 395 | any liability that these contractual assumptions directly impose on 396 | those licensors and authors. 397 | 398 | All other non-permissive additional terms are considered "further 399 | restrictions" within the meaning of section 10. If the Program as you 400 | received it, or any part of it, contains a notice stating that it is 401 | governed by this License along with a term that is a further 402 | restriction, you may remove that term. If a license document contains 403 | a further restriction but permits relicensing or conveying under this 404 | License, you may add to a covered work material governed by the terms 405 | of that license document, provided that the further restriction does 406 | not survive such relicensing or conveying. 407 | 408 | If you add terms to a covered work in accord with this section, you 409 | must place, in the relevant source files, a statement of the 410 | additional terms that apply to those files, or a notice indicating 411 | where to find the applicable terms. 412 | 413 | Additional terms, permissive or non-permissive, may be stated in the 414 | form of a separately written license, or stated as exceptions; 415 | the above requirements apply either way. 416 | 417 | 8. Termination. 418 | 419 | You may not propagate or modify a covered work except as expressly 420 | provided under this License. Any attempt otherwise to propagate or 421 | modify it is void, and will automatically terminate your rights under 422 | this License (including any patent licenses granted under the third 423 | paragraph of section 11). 424 | 425 | However, if you cease all violation of this License, then your 426 | license from a particular copyright holder is reinstated (a) 427 | provisionally, unless and until the copyright holder explicitly and 428 | finally terminates your license, and (b) permanently, if the copyright 429 | holder fails to notify you of the violation by some reasonable means 430 | prior to 60 days after the cessation. 431 | 432 | Moreover, your license from a particular copyright holder is 433 | reinstated permanently if the copyright holder notifies you of the 434 | violation by some reasonable means, this is the first time you have 435 | received notice of violation of this License (for any work) from that 436 | copyright holder, and you cure the violation prior to 30 days after 437 | your receipt of the notice. 438 | 439 | Termination of your rights under this section does not terminate the 440 | licenses of parties who have received copies or rights from you under 441 | this License. If your rights have been terminated and not permanently 442 | reinstated, you do not qualify to receive new licenses for the same 443 | material under section 10. 444 | 445 | 9. Acceptance Not Required for Having Copies. 446 | 447 | You are not required to accept this License in order to receive or 448 | run a copy of the Program. Ancillary propagation of a covered work 449 | occurring solely as a consequence of using peer-to-peer transmission 450 | to receive a copy likewise does not require acceptance. However, 451 | nothing other than this License grants you permission to propagate or 452 | modify any covered work. These actions infringe copyright if you do 453 | not accept this License. Therefore, by modifying or propagating a 454 | covered work, you indicate your acceptance of this License to do so. 455 | 456 | 10. Automatic Licensing of Downstream Recipients. 457 | 458 | Each time you convey a covered work, the recipient automatically 459 | receives a license from the original licensors, to run, modify and 460 | propagate that work, subject to this License. You are not responsible 461 | for enforcing compliance by third parties with this License. 462 | 463 | An "entity transaction" is a transaction transferring control of an 464 | organization, or substantially all assets of one, or subdividing an 465 | organization, or merging organizations. If propagation of a covered 466 | work results from an entity transaction, each party to that 467 | transaction who receives a copy of the work also receives whatever 468 | licenses to the work the party's predecessor in interest had or could 469 | give under the previous paragraph, plus a right to possession of the 470 | Corresponding Source of the work from the predecessor in interest, if 471 | the predecessor has it or can get it with reasonable efforts. 472 | 473 | You may not impose any further restrictions on the exercise of the 474 | rights granted or affirmed under this License. For example, you may 475 | not impose a license fee, royalty, or other charge for exercise of 476 | rights granted under this License, and you may not initiate litigation 477 | (including a cross-claim or counterclaim in a lawsuit) alleging that 478 | any patent claim is infringed by making, using, selling, offering for 479 | sale, or importing the Program or any portion of it. 480 | 481 | 11. Patents. 482 | 483 | A "contributor" is a copyright holder who authorizes use under this 484 | License of the Program or a work on which the Program is based. The 485 | work thus licensed is called the contributor's "contributor version". 486 | 487 | A contributor's "essential patent claims" are all patent claims 488 | owned or controlled by the contributor, whether already acquired or 489 | hereafter acquired, that would be infringed by some manner, permitted 490 | by this License, of making, using, or selling its contributor version, 491 | but do not include claims that would be infringed only as a 492 | consequence of further modification of the contributor version. For 493 | purposes of this definition, "control" includes the right to grant 494 | patent sublicenses in a manner consistent with the requirements of 495 | this License. 496 | 497 | Each contributor grants you a non-exclusive, worldwide, royalty-free 498 | patent license under the contributor's essential patent claims, to 499 | make, use, sell, offer for sale, import and otherwise run, modify and 500 | propagate the contents of its contributor version. 501 | 502 | In the following three paragraphs, a "patent license" is any express 503 | agreement or commitment, however denominated, not to enforce a patent 504 | (such as an express permission to practice a patent or covenant not to 505 | sue for patent infringement). To "grant" such a patent license to a 506 | party means to make such an agreement or commitment not to enforce a 507 | patent against the party. 508 | 509 | If you convey a covered work, knowingly relying on a patent license, 510 | and the Corresponding Source of the work is not available for anyone 511 | to copy, free of charge and under the terms of this License, through a 512 | publicly available network server or other readily accessible means, 513 | then you must either (1) cause the Corresponding Source to be so 514 | available, or (2) arrange to deprive yourself of the benefit of the 515 | patent license for this particular work, or (3) arrange, in a manner 516 | consistent with the requirements of this License, to extend the patent 517 | license to downstream recipients. "Knowingly relying" means you have 518 | actual knowledge that, but for the patent license, your conveying the 519 | covered work in a country, or your recipient's use of the covered work 520 | in a country, would infringe one or more identifiable patents in that 521 | country that you have reason to believe are valid. 522 | 523 | If, pursuant to or in connection with a single transaction or 524 | arrangement, you convey, or propagate by procuring conveyance of, a 525 | covered work, and grant a patent license to some of the parties 526 | receiving the covered work authorizing them to use, propagate, modify 527 | or convey a specific copy of the covered work, then the patent license 528 | you grant is automatically extended to all recipients of the covered 529 | work and works based on it. 530 | 531 | A patent license is "discriminatory" if it does not include within 532 | the scope of its coverage, prohibits the exercise of, or is 533 | conditioned on the non-exercise of one or more of the rights that are 534 | specifically granted under this License. You may not convey a covered 535 | work if you are a party to an arrangement with a third party that is 536 | in the business of distributing software, under which you make payment 537 | to the third party based on the extent of your activity of conveying 538 | the work, and under which the third party grants, to any of the 539 | parties who would receive the covered work from you, a discriminatory 540 | patent license (a) in connection with copies of the covered work 541 | conveyed by you (or copies made from those copies), or (b) primarily 542 | for and in connection with specific products or compilations that 543 | contain the covered work, unless you entered into that arrangement, 544 | or that patent license was granted, prior to 28 March 2007. 545 | 546 | Nothing in this License shall be construed as excluding or limiting 547 | any implied license or other defenses to infringement that may 548 | otherwise be available to you under applicable patent law. 549 | 550 | 12. No Surrender of Others' Freedom. 551 | 552 | If conditions are imposed on you (whether by court order, agreement or 553 | otherwise) that contradict the conditions of this License, they do not 554 | excuse you from the conditions of this License. If you cannot convey a 555 | covered work so as to satisfy simultaneously your obligations under this 556 | License and any other pertinent obligations, then as a consequence you may 557 | not convey it at all. For example, if you agree to terms that obligate you 558 | to collect a royalty for further conveying from those to whom you convey 559 | the Program, the only way you could satisfy both those terms and this 560 | License would be to refrain entirely from conveying the Program. 561 | 562 | 13. Use with the GNU Affero General Public License. 563 | 564 | Notwithstanding any other provision of this License, you have 565 | permission to link or combine any covered work with a work licensed 566 | under version 3 of the GNU Affero General Public License into a single 567 | combined work, and to convey the resulting work. The terms of this 568 | License will continue to apply to the part which is the covered work, 569 | but the special requirements of the GNU Affero General Public License, 570 | section 13, concerning interaction through a network will apply to the 571 | combination as such. 572 | 573 | 14. Revised Versions of this License. 574 | 575 | The Free Software Foundation may publish revised and/or new versions of 576 | the GNU General Public License from time to time. Such new versions will 577 | be similar in spirit to the present version, but may differ in detail to 578 | address new problems or concerns. 579 | 580 | Each version is given a distinguishing version number. If the 581 | Program specifies that a certain numbered version of the GNU General 582 | Public License "or any later version" applies to it, you have the 583 | option of following the terms and conditions either of that numbered 584 | version or of any later version published by the Free Software 585 | Foundation. If the Program does not specify a version number of the 586 | GNU General Public License, you may choose any version ever published 587 | by the Free Software Foundation. 588 | 589 | If the Program specifies that a proxy can decide which future 590 | versions of the GNU General Public License can be used, that proxy's 591 | public statement of acceptance of a version permanently authorizes you 592 | to choose that version for the Program. 593 | 594 | Later license versions may give you additional or different 595 | permissions. However, no additional obligations are imposed on any 596 | author or copyright holder as a result of your choosing to follow a 597 | later version. 598 | 599 | 15. Disclaimer of Warranty. 600 | 601 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 602 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 603 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 604 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 605 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 606 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 607 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 608 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 609 | 610 | 16. Limitation of Liability. 611 | 612 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 613 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 614 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 615 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 616 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 617 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 618 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 619 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 620 | SUCH DAMAGES. 621 | 622 | 17. Interpretation of Sections 15 and 16. 623 | 624 | If the disclaimer of warranty and limitation of liability provided 625 | above cannot be given local legal effect according to their terms, 626 | reviewing courts shall apply local law that most closely approximates 627 | an absolute waiver of all civil liability in connection with the 628 | Program, unless a warranty or assumption of liability accompanies a 629 | copy of the Program in return for a fee. 630 | 631 | - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 632 | 633 | The quantization and dithering code in pngquant is lifted from Jef Poskanzer's 634 | 'ppmquant', part of his wonderful PBMPLUS tool suite. 635 | 636 | Greg Roelofs hacked it into a (in his words) "slightly cheesy" 'pamquant' back 637 | in 1997 (see http://pobox.com/~newt/greg_rgba.html) and finally he ripped out 638 | the cheesy file-I/O parts and replaced them with nice PNG code in December 639 | 2000. The PNG reading and writing code is a merged and slightly simplified 640 | version of readpng, readpng2, and writepng from his book "PNG: The Definitive 641 | Guide." 642 | In 2014 Greg has relicensed the code under the simplified BSD license. 643 | 644 | Note that both licenses are basically BSD-like; that is, use the code however 645 | you like, as long as you acknowledge its origins. 646 | 647 | - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 648 | 649 | pngquant.c: 650 | 651 | © 1989, 1991 by Jef Poskanzer. 652 | 653 | Permission to use, copy, modify, and distribute this software and its 654 | documentation for any purpose and without fee is hereby granted, provided 655 | that the above copyright notice appear in all copies and that both that 656 | copyright notice and this permission notice appear in supporting 657 | documentation. This software is provided "as is" without express or 658 | implied warranty. 659 | 660 | - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 661 | 662 | pngquant.c and rwpng.c/h: 663 | 664 | © 1997-2002 by Greg Roelofs; based on an idea by Stefan Schneider. 665 | 666 | All rights reserved. 667 | 668 | Redistribution and use in source and binary forms, with or without modification, 669 | are permitted provided that the following conditions are met: 670 | 671 | 1. Redistributions of source code must retain the above copyright notice, 672 | this list of conditions and the following disclaimer. 673 | 674 | 2. Redistributions in binary form must reproduce the above copyright notice, 675 | this list of conditions and the following disclaimer in the documentation 676 | and/or other materials provided with the distribution. 677 | 678 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 679 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 680 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 681 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 682 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 683 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 684 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 685 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 686 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 687 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 688 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "pngquant" 3 | version = "3.0.3" 4 | authors = ["Kornel Lesiński "] 5 | description = "Convert 24/32-bit PNG images to efficient 8-bit format with alpha channel" 6 | build = "rust/build.rs" 7 | categories = ["multimedia::images"] 8 | homepage = "https://pngquant.org" 9 | documentation = "https://github.com/kornelski/pngquant#readme" 10 | include = ["/rwpng*.[ch]", "/pngquant.c","/pngquant_opts.[ch]", "/rust/*.rs", "/COPYRIGHT", "/Cargo.toml", "/README.md", "/pngquant.1"] 11 | keywords = ["quantization", "palette", "image", "pngquant", "compression"] 12 | license = "GPL-3.0-or-later" 13 | readme = "README.md" 14 | repository = "https://github.com/kornelski/pngquant.git" 15 | edition = "2021" 16 | rust-version = "1.63" 17 | 18 | [[bin]] 19 | name = "pngquant" 20 | path = "rust/bin.rs" 21 | 22 | [build-dependencies] 23 | cc = "1.0.72" 24 | dunce = "1.0.4" 25 | 26 | [dependencies] 27 | getopts = "0.2.21" 28 | libc = "0.2.112" 29 | libpng-sys = "1.1.9" 30 | wild = "2.2.0" 31 | imagequant-sys = { version = "4.0.3", path = "lib/imagequant-sys" } 32 | 33 | [dependencies.cocoa_image] 34 | optional = true 35 | version = "1.0.6" 36 | 37 | [dependencies.lcms2-sys] 38 | optional = true 39 | version = "4.0.3" 40 | 41 | [features] 42 | cocoa = ["dep:cocoa_image"] 43 | default = ["lcms2"] 44 | lcms2 = ["dep:lcms2-sys"] 45 | lcms2-static = ["lcms2", "lcms2-sys?/static"] 46 | png-static = ["libpng-sys/static"] 47 | z-static = ["libpng-sys/static-libz"] 48 | static = ["lcms2-static", "png-static"] 49 | 50 | [profile.release] 51 | opt-level = 3 52 | codegen-units = 1 53 | lto = true 54 | panic = "abort" 55 | 56 | [package.metadata.docs.rs] 57 | targets = ["x86_64-unknown-linux-gnu"] 58 | rustdoc-args = ["--generate-link-to-definition"] 59 | -------------------------------------------------------------------------------- /INSTALL: -------------------------------------------------------------------------------- 1 | ## Compiling via Rust/Cargo 2 | 3 | The old `configure && make` method is no longer supported. 4 | 5 | ### Prerequisites 6 | 7 | Install Rust 1.70 or later: https://rustup.rs 8 | 9 | On Windows also install msys-git and Visual C++ Build Tools 10 | with Windows 8/10/11 SDK enabled, and reboot. 11 | 12 | ### Building 13 | 14 | Get the code by cloning *recursively*: 15 | 16 | # Unix version 17 | git clone --recursive https://github.com/kornelski/pngquant.git 18 | 19 | # Windows version 20 | git clone -b msvc --recursive https://github.com/kornelski/pngquant.git 21 | 22 | And then build: 23 | 24 | cd pngquant 25 | cargo build --release 26 | 27 | This will create executable in `target/release/pngquant`(`.exe`). 28 | 29 | You can build with additional features: 30 | 31 | cargo build --release --features=lcms2 32 | 33 | The features are: 34 | 35 | * `lcms2` — compile with support for color profiles via Little CMS. 36 | * `lcms2-static` — same, but link statically. 37 | * `cocoa` — compile with support for color profiles via macOS Cocoa. 38 | 39 | ## Compilation with Cocoa image reader 40 | 41 | macOS version can use Cocoa to read images. This adds support for color profiles 42 | and other image formats as input. However, it also disables support for preserving PNG metadata. 43 | 44 | cargo build --release --features=cocoa 45 | 46 | ## Compilation with Little CMS 2 47 | 48 | Little CMS library is used by default. 49 | 50 | It's linked dynamically if `pkg-config` is working (e.g. install `liblcms2-dev`). 51 | Otherwise uses static build as a fallback. 52 | 53 | Set `export LCMS2_STATIC=1` or build `--features=lcms2-static` to force static linking. 54 | 55 | ## Compilation of `libimagequant_sys.a` only 56 | 57 | If you want to use pngquant's conversion algorithm without loading/saving PNG 58 | files, then you can run `cargo build --release` in the `lib/` directory. 59 | 60 | The imagequant library doesn't need libpng nor zlib. 61 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # pngquant 3 [![CI](https://github.com/kornelski/pngquant/actions/workflows/ci.yml/badge.svg)](https://github.com/kornelski/pngquant/actions/workflows/ci.yml) 2 | 3 | [pngquant](https://pngquant.org) is a PNG compressor that significantly reduces file sizes by converting images to a more efficient 8-bit PNG format *with alpha channel* (often 60-80% smaller than 24/32-bit PNG files). Compressed images are fully standards-compliant and are supported by all web browsers and operating systems. 4 | 5 | [This](https://github.com/kornelski/pngquant) is the official `pngquant` repository. The compression engine is also available [as an embeddable library](https://github.com/ImageOptim/libimagequant). 6 | 7 | ## Usage 8 | 9 | - batch conversion of multiple files: `pngquant *.png` 10 | - Unix-style stdin/stdout chaining: `… | pngquant - | …` 11 | 12 | To further reduce file size, try [oxipng](https://lib.rs/oxipng), [ImageOptim](https://imageoptim.com), or [zopflipng](https://github.com/google/zopfli). 13 | 14 | ## Features 15 | 16 | * High-quality palette generation 17 | - advanced quantization algorithm with support for gamma correction and premultiplied alpha 18 | - unique dithering algorithm that does not add unnecessary noise to the image 19 | 20 | * Configurable quality level 21 | - automatically finds required number of colors and can skip images which can't be converted with the desired quality 22 | 23 | * Fast, modern code 24 | - based on a portable [libimagequant library](https://github.com/ImageOptim/libimagequant) 25 | - C99 with no workarounds for legacy systems or compilers ([apart from Visual Studio](https://github.com/kornelski/pngquant/tree/msvc)) 26 | - multicore support (via OpenMP) and Intel SSE optimizations 27 | 28 | ## Options 29 | 30 | See `pngquant -h` for full list. 31 | 32 | ### `--quality min-max` 33 | 34 | `min` and `max` are numbers in range 0 (worst) to 100 (perfect), similar to JPEG. pngquant will use the least amount of colors required to meet or exceed the `max` quality. If conversion results in quality below the `min` quality the image won't be saved (if outputting to stdin, 24-bit original will be output) and pngquant will exit with status code 99. 35 | 36 | pngquant --quality=65-80 image.png 37 | 38 | ### `--ext new.png` 39 | 40 | Set custom extension (suffix) for output filename. By default `-or8.png` or `-fs8.png` is used. If you use `--ext=.png --force` options pngquant will overwrite input files in place (use with caution). 41 | 42 | ### `-o out.png` or `--output out.png` 43 | 44 | Writes converted file to the given path. When this option is used only single input file is allowed. 45 | 46 | ### `--skip-if-larger` 47 | 48 | Don't write converted files if the conversion isn't worth it. 49 | 50 | ### `--speed N` 51 | 52 | Speed/quality trade-off from 1 (slowest, highest quality, smallest files) to 11 (fastest, less consistent quality, light comperssion). The default is 4. It's recommended to keep the default, unless you need to generate images in real time (e.g. map tiles). Higher speeds are fine with 256 colors, but don't handle lower number of colors well. 53 | 54 | ### `--nofs` 55 | 56 | Disables Floyd-Steinberg dithering. 57 | 58 | ### `--floyd=0.5` 59 | 60 | Controls level of dithering (0 = none, 1 = full). Note that the `=` character is required. 61 | 62 | ### `--posterize bits` 63 | 64 | Reduce precision of the palette by number of bits. Use when the image will be displayed on low-depth screens (e.g. 16-bit displays or compressed textures in ARGB444 format). 65 | 66 | ### `--strip` 67 | 68 | Don't copy optional PNG chunks. Metadata is always removed on Mac (when using Cocoa reader). 69 | 70 | See [man page](https://github.com/kornelski/pngquant/blob/master/pngquant.1) (`man pngquant`) for the full list of options. 71 | 72 | ## License 73 | 74 | pngquant is dual-licensed: 75 | 76 | * Under **GPL v3** or later with an additional [copyright notice](https://github.com/kornelski/pngquant/blob/master/COPYRIGHT) that must be kept for the older parts of the code. 77 | 78 | * Or [a **commercial license**](https://supso.org/projects/pngquant) for use in non-GPL software (e.g. closed-source or App Store distribution). You can [get the license via Super Source](https://supso.org/projects/pngquant). Email kornel@pngquant.org if you have any questions. 79 | -------------------------------------------------------------------------------- /pngquant.1: -------------------------------------------------------------------------------- 1 | .Dd 2013-02-25 2 | .Dt pngquant 1 3 | .Sh NAME 4 | .Nm pngquant 5 | .Nd PNG converter and lossy image compressor 6 | .Sh SYNOPSIS 7 | .Nm 8 | .Aq options 9 | .Op ncolors 10 | .Pa file 11 | .Op Ar 12 | .Nm 13 | .Aq options 14 | .Op ncolors 15 | .Fl 16 | .Cm < Ns Pa file 17 | .Cm > Ns Pa file 18 | .Sh DESCRIPTION 19 | .Nm 20 | converts 32-bit RGBA PNGs to 8-bit (or smaller) RGBA-palette PNGs, optionally using Floyd-Steinberg dithering. 21 | The output filename is the same as the input name except that it ends in 22 | .Ql -fs8.png 23 | or 24 | .Ql -or8.png 25 | (unless the input is stdin, in which case the quantized image will go to stdout). 26 | The default behavior if the output file exists is to skip the conversion; use 27 | .Fl Fl force 28 | to overwrite. 29 | .Sh OPTIONS 30 | .Bl -tag -width -indent 31 | .It Fl o Ar out.png , Fl Fl output Ar out.png 32 | Writes converted file to the given path. When this option is used only single input file is allowed. 33 | .It Fl Fl ext Ar new.png 34 | File extension (suffix) to use for output files instead of the default 35 | .Ql -fs8.png 36 | or 37 | .Ql -or8.png . 38 | .It Fl f , Fl Fl force 39 | Overwrite existing output files. 40 | .Do 41 | .Fl Fl ext 42 | .Ar .png 43 | .Fl Fl force 44 | .Dc 45 | can be used to convert files in place (which is unsafe). 46 | .It Fl Fl nofs , Fl Fl ordered 47 | Disable Floyd-Steinberg dithering. 48 | .It Fl Fl floyd Op Ar =N 49 | Set dithering level using fractional number between 50 | .Cm 0 51 | (none) and 52 | .Cm 1 53 | (full, the default). 54 | .It Fl s Ar N , Fl Fl speed Ar N 55 | .Cm 1 56 | (brute-force) to 57 | .Cm 11 58 | (fastest). The default is 59 | .Cm 3 . 60 | Speed 61 | .Cm 10 62 | has 5% lower quality, but is about 8 times faster than the default. Speed 11 disables dithering and lowers compression level. 63 | .It Fl Q Ar min-max , Fl Fl quality Ar min-max 64 | .Va min 65 | and 66 | .Va max 67 | are numbers in range 68 | .Cm 0 69 | (worst) to 70 | .Cm 100 71 | (perfect), similar to JPEG. 72 | .Nm 73 | will use the least amount of colors required to meet or exceed the 74 | .Va max 75 | quality. If conversion results in quality below the 76 | .Va min 77 | quality the image won't be saved (or if outputting to stdin, 24-bit original will be output) and pngquant will exit with status code 78 | .Er 99 . 79 | .It Fl Fl skip-if-larger 80 | If conversion results in a file larger than the original, the image won't be saved and pngquant will exit with status code 81 | .Er 98 . 82 | Additionally, file size gain must be greater than the amount of quality lost. If quality drops by 50%, it will expect 50% file size reduction to consider it worthwhile. 83 | .It Fl Fl posterize Ar bits 84 | Truncate number of least significant bits of color (per channel). Use this when image will be output on low-depth displays (e.g. 16-bit RGB). 85 | .Nm 86 | will make almost-opaque pixels fully opaque and will reduce amount of semi-transparent colors. When this option is enabled the default filename suffix is 87 | .Ql -ie-fs8.png 88 | / 89 | .Ql -ie-or8.png . 90 | .It Fl Fl strip 91 | Remove optional chunks (metadata) from PNG files. 92 | .It Fl Fl transbug 93 | Workaround for readers that expect fully transparent color to be the last entry in the palette. 94 | .It Fl v , Fl Fl verbose 95 | Enable verbose messages showing progress and information about input/output. Opposite is 96 | .Fl Fl quiet . 97 | Errors are output to 98 | .Pa stderr 99 | regardless of this option. 100 | .It Fl V , Fl Fl version 101 | Display version on 102 | .Pa stdout 103 | and exit. 104 | .It Fl h , Fl Fl help 105 | Display help and exit. 106 | .El 107 | .Sh EXAMPLE 108 | Creating a new image with the number of colors reduced to 64: 109 | .Bd -ragged -offset indent 110 | .Nm 111 | .Cm 64 image.png 112 | .Ed 113 | .Pp 114 | The resulting image will have 64 colors and will be saved as 115 | .Pa image-fs8.png . 116 | .Pp 117 | Overwriting image in-place if it can be reduced without too much quality loss: 118 | .Bd -ragged -offset indent 119 | .Nm 120 | .Cm -f --ext .png --quality 70-95 image.png 121 | .Ed 122 | .Sh AUTHOR 123 | .Nm 124 | is developed by Kornel Lesinski 125 | .Aq Mt kornel@pngquant.org 126 | based on code by Greg Roelofs 127 | .Aq Mt newt@pobox.com . 128 | .Pp 129 | .Lk https://pngquant.org "pngquant homepage" . 130 | -------------------------------------------------------------------------------- /pngquant.c: -------------------------------------------------------------------------------- 1 | /* pngquant.c - quantize the colors in an alphamap down to a specified number 2 | ** 3 | ** © 2009-2019 by Kornel Lesiński. 4 | ** © 1989, 1991 by Jef Poskanzer. 5 | ** © 1997-2002 by Greg Roelofs; based on an idea by Stefan Schneider. 6 | ** 7 | ** See COPYRIGHT file for license. 8 | */ 9 | 10 | char *PNGQUANT_USAGE = "\ 11 | usage: pngquant [options] [ncolors] -- pngfile [pngfile ...]\n\ 12 | pngquant [options] [ncolors] - >stdout 36 | #include 37 | #include 38 | #include 39 | #include 40 | #include 41 | 42 | #if defined(_WIN32) || defined(WIN32) || defined(__WIN32__) 43 | #include /* O_BINARY */ 44 | #include /* setmode() */ 45 | #include /* UTF-8 locale */ 46 | #else 47 | #include 48 | #endif 49 | 50 | #ifdef _OPENMP 51 | #include 52 | #else 53 | #define omp_get_max_threads() 1 54 | #define omp_get_thread_num() 0 55 | #endif 56 | 57 | #include "rwpng.h" /* typedefs, common macros, public prototypes */ 58 | #include "libimagequant.h" /* if it fails here, run: git submodule update or add -Ilib to compiler flags */ 59 | #include "pngquant_opts.h" 60 | 61 | char *PNGQUANT_VERSION = LIQ_VERSION_STRING " (January 2022)"; 62 | 63 | static pngquant_error prepare_output_image(liq_result *result, liq_image *input_image, rwpng_color_transform tag, png8_image *output_image); 64 | static void set_palette(liq_result *result, png8_image *output_image); 65 | static pngquant_error read_image(liq_attr *options, const char *filename, int using_stdin, png24_image *input_image_p, liq_image **liq_image_p, bool keep_input_pixels, bool strip, bool verbose); 66 | static pngquant_error write_image(png8_image *output_image, png24_image *output_image24, const char *outname, struct pngquant_options *options, liq_attr *liq); 67 | static char *add_filename_extension(const char *filename, const char *newext); 68 | static bool file_exists(const char *outname); 69 | 70 | static void verbose_printf(liq_attr *liq, struct pngquant_options *context, const char *fmt, ...) 71 | { 72 | if (context->log_callback) { 73 | va_list va; 74 | va_start(va, fmt); 75 | int required_space = vsnprintf(NULL, 0, fmt, va)+1; // +\0 76 | va_end(va); 77 | 78 | #if defined(_MSC_VER) 79 | char *buf = malloc(required_space); 80 | #else 81 | char buf[required_space]; 82 | #endif 83 | va_start(va, fmt); 84 | vsnprintf(buf, required_space, fmt, va); 85 | va_end(va); 86 | 87 | context->log_callback(liq, buf, context->log_callback_user_info); 88 | #if defined(_MSC_VER) 89 | free(buf); 90 | #endif 91 | } 92 | } 93 | 94 | static void log_callback(const liq_attr *attr, const char *msg, void* user_info) 95 | { 96 | fprintf(stderr, "%s\n", msg); 97 | } 98 | 99 | #ifdef _OPENMP 100 | #define LOG_BUFFER_SIZE 1300 101 | struct buffered_log { 102 | int buf_used; 103 | char buf[LOG_BUFFER_SIZE]; 104 | }; 105 | 106 | static void log_callback_buferred_flush(const liq_attr *attr, void *context) 107 | { 108 | struct buffered_log *log = context; 109 | if (log->buf_used) { 110 | fwrite(log->buf, 1, log->buf_used, stderr); 111 | fflush(stderr); 112 | log->buf_used = 0; 113 | } 114 | } 115 | 116 | static void log_callback_buferred(const liq_attr *attr, const char *msg, void* context) 117 | { 118 | struct buffered_log *log = context; 119 | int len = strlen(msg); 120 | if (len > LOG_BUFFER_SIZE-2) len = LOG_BUFFER_SIZE-2; 121 | 122 | if (len > LOG_BUFFER_SIZE - log->buf_used - 2) log_callback_buferred_flush(attr, log); 123 | memcpy(&log->buf[log->buf_used], msg, len); 124 | log->buf_used += len+1; 125 | log->buf[log->buf_used-1] = '\n'; 126 | log->buf[log->buf_used] = '\0'; 127 | } 128 | #endif 129 | 130 | void pngquant_internal_print_config(FILE *fd) { 131 | fputs("" 132 | #ifndef NDEBUG 133 | " WARNING: this is a DEBUG (slow) version.\n" /* NDEBUG disables assert() */ 134 | #endif 135 | #if !USE_SSE && (defined(__SSE__) || defined(__amd64__) || defined(__X86_64__) || defined(__i386__)) 136 | " SSE acceleration disabled.\n" 137 | #endif 138 | #if _OPENMP 139 | " Compiled with OpenMP (multicore support).\n" 140 | #endif 141 | , fd); 142 | fflush(fd); 143 | } 144 | 145 | FILE *pngquant_c_stderr() { 146 | return stderr; 147 | } 148 | FILE *pngquant_c_stdout() { 149 | return stdout; 150 | } 151 | 152 | static void print_full_version(FILE *fd) 153 | { 154 | fprintf(fd, "pngquant, %s, by Kornel Lesinski, Greg Roelofs.\n", PNGQUANT_VERSION); 155 | pngquant_internal_print_config(fd); 156 | rwpng_version_info(fd); 157 | fputs("\n", fd); 158 | } 159 | 160 | static void print_usage(FILE *fd) 161 | { 162 | fputs(PNGQUANT_USAGE, fd); 163 | } 164 | 165 | /** 166 | * N = automatic quality, uses limit unless force is set (N-N or 0-N) 167 | * -N = no better than N (same as 0-N) 168 | * N-M = no worse than N, no better than M 169 | * N- = no worse than N, perfect if possible (same as N-100) 170 | * 171 | * where N,M are numbers between 0 (lousy) and 100 (perfect) 172 | */ 173 | static bool parse_quality(const char *quality, liq_attr *options, bool *min_quality_limit) 174 | { 175 | long limit, target; 176 | const char *str = quality; char *end; 177 | 178 | long t1 = strtol(str, &end, 10); 179 | if (str == end) return false; 180 | str = end; 181 | 182 | if ('\0' == end[0] && t1 < 0) { // quality="-%d" 183 | target = -t1; 184 | limit = 0; 185 | } else if ('\0' == end[0]) { // quality="%d" 186 | target = t1; 187 | limit = t1*9/10; 188 | } else if ('-' == end[0] && '\0' == end[1]) { // quality="%d-" 189 | target = 100; 190 | limit = t1; 191 | } else { // quality="%d-%d" 192 | long t2 = strtol(str, &end, 10); 193 | if (str == end || t2 > 0) return false; 194 | target = -t2; 195 | limit = t1; 196 | } 197 | 198 | *min_quality_limit = (limit > 0); 199 | return LIQ_OK == liq_set_quality(options, limit, target); 200 | } 201 | 202 | pngquant_error pngquant_main_internal(struct pngquant_options *options, liq_attr *liq); 203 | static pngquant_error pngquant_file_internal(const char *filename, const char *outname, struct pngquant_options *options, liq_attr *liq); 204 | 205 | #ifndef PNGQUANT_NO_MAIN 206 | int main(int argc, char *argv[]) 207 | { 208 | struct pngquant_options options = { 209 | .floyd = 1.f, // floyd-steinberg dithering 210 | .strip = false, 211 | }; 212 | 213 | pngquant_error retval = pngquant_parse_options(argc, argv, &options); 214 | if (retval != SUCCESS) { 215 | return retval; 216 | } 217 | 218 | if (options.print_version) { 219 | puts(PNGQUANT_VERSION); 220 | return SUCCESS; 221 | } 222 | 223 | if (options.missing_arguments) { 224 | print_full_version(stderr); 225 | print_usage(stderr); 226 | return MISSING_ARGUMENT; 227 | } 228 | 229 | if (options.print_help) { 230 | print_full_version(stdout); 231 | print_usage(stdout); 232 | return SUCCESS; 233 | } 234 | 235 | #if defined(_WIN32) || defined(WIN32) || defined(__WIN32__) 236 | setlocale(LC_ALL, ".65001"); // issue #376; set UTF-8 for Unicode filenames 237 | #endif 238 | 239 | liq_attr *liq = liq_attr_create(); 240 | 241 | if (!liq) { 242 | fputs("SSE-capable CPU is required for this build.\n", stderr); 243 | return WRONG_ARCHITECTURE; 244 | } 245 | 246 | if (options.quality && !parse_quality(options.quality, liq, &options.min_quality_limit)) { 247 | fputs("Quality should be in format min-max where min and max are numbers in range 0-100.\n", stderr); 248 | return INVALID_ARGUMENT; 249 | } 250 | 251 | if (options.iebug) { 252 | // opacities above 238 will be rounded up to 255, because IE6 truncates <255 to 0. 253 | liq_set_min_opacity(liq, 238); 254 | fputs(" warning: the workaround for IE6 is deprecated\n", stderr); 255 | } 256 | 257 | if (options.verbose) { 258 | liq_set_log_callback(liq, log_callback, NULL); 259 | options.log_callback = log_callback; 260 | } 261 | 262 | if (options.last_index_transparent) { 263 | liq_set_last_index_transparent(liq, true); 264 | } 265 | 266 | if (options.speed >= 10) { 267 | options.fast_compression = true; 268 | if (options.speed == 11) { 269 | options.floyd = 0; 270 | options.speed = 10; 271 | } 272 | } 273 | 274 | if (options.speed && LIQ_OK != liq_set_speed(liq, options.speed)) { 275 | fputs("Speed should be between 1 (slow) and 11 (fast).\n", stderr); 276 | return INVALID_ARGUMENT; 277 | } 278 | 279 | if (options.colors && LIQ_OK != liq_set_max_colors(liq, options.colors)) { 280 | fputs("Number of colors must be between 2 and 256.\n", stderr); 281 | return INVALID_ARGUMENT; 282 | } 283 | 284 | if (options.posterize && LIQ_OK != liq_set_min_posterization(liq, options.posterize)) { 285 | fputs("Posterization should be number of bits in range 0-4.\n", stderr); 286 | return INVALID_ARGUMENT; 287 | } 288 | 289 | if (options.extension && options.output_file_path) { 290 | fputs("--ext and --output options can't be used at the same time\n", stderr); 291 | return INVALID_ARGUMENT; 292 | } 293 | 294 | // new filename extension depends on options used. Typically basename-fs8.png 295 | if (options.extension == NULL) { 296 | options.extension = options.floyd > 0 ? "-fs8.png" : "-or8.png"; 297 | } 298 | 299 | if (options.output_file_path && options.num_files != 1) { 300 | fputs(" error: Only one input file is allowed when --output is used. This error also happens when filenames with spaces are not in quotes.\n", stderr); 301 | return INVALID_ARGUMENT; 302 | } 303 | 304 | if (options.using_stdout && !options.using_stdin && options.num_files != 1) { 305 | fputs(" error: Only one input file is allowed when using the special output path \"-\" to write to stdout. This error also happens when filenames with spaces are not in quotes.\n", stderr); 306 | return INVALID_ARGUMENT; 307 | } 308 | 309 | if (!options.num_files && !options.using_stdin) { 310 | fputs("No input files specified.\n", stderr); 311 | if (options.verbose) { 312 | print_full_version(stderr); 313 | } 314 | print_usage(stderr); 315 | return MISSING_ARGUMENT; 316 | } 317 | 318 | retval = pngquant_main_internal(&options, liq); 319 | liq_attr_destroy(liq); 320 | return retval; 321 | } 322 | #endif 323 | 324 | // Don't use this. This is not a public API. 325 | pngquant_error pngquant_main_internal(struct pngquant_options *options, liq_attr *liq) 326 | { 327 | #if defined(_WIN32) || defined(WIN32) || defined(__WIN32__) 328 | setlocale(LC_ALL, ".65001"); // issue #376; set UTF-8 for Unicode filenames 329 | #endif 330 | 331 | if (options->map_file) { 332 | png24_image tmp = {.width=0}; 333 | if (SUCCESS != read_image(liq, options->map_file, false, &tmp, &options->fixed_palette_image, true, true, false)) { 334 | fprintf(stderr, " error: unable to load %s", options->map_file); 335 | return INVALID_ARGUMENT; 336 | } 337 | liq_result *tmp_quantize = liq_quantize_image(liq, options->fixed_palette_image); 338 | const liq_palette *pal = liq_get_palette(tmp_quantize); 339 | if (!pal) { 340 | fprintf(stderr, " error: unable to read colors from %s", options->map_file); 341 | return INVALID_ARGUMENT; 342 | } 343 | for(unsigned int i=0; i < pal->count; i++) { 344 | liq_image_add_fixed_color(options->fixed_palette_image, pal->entries[i]); 345 | } 346 | liq_result_destroy(tmp_quantize); 347 | } 348 | 349 | #ifdef _OPENMP 350 | // if there's a lot of files, coarse parallelism can be used 351 | if (options->num_files > 2*omp_get_max_threads()) { 352 | omp_set_nested(0); 353 | omp_set_dynamic(1); 354 | } else { 355 | omp_set_nested(1); 356 | } 357 | #endif 358 | 359 | unsigned int error_count=0, skipped_count=0, file_count=0; 360 | pngquant_error latest_error=SUCCESS; 361 | 362 | #pragma omp parallel for \ 363 | schedule(static, 1) reduction(+:skipped_count) reduction(+:error_count) reduction(+:file_count) shared(latest_error) 364 | for(int i=0; i < options->num_files; i++) { 365 | const char *filename = options->using_stdin ? "stdin" : options->files[i]; 366 | struct pngquant_options opts = *options; 367 | liq_attr *local_liq = liq_attr_copy(liq); 368 | 369 | 370 | #ifdef _OPENMP 371 | struct buffered_log buf = {0}; 372 | if (opts.log_callback && omp_get_num_threads() > 1 && opts.num_files > 1) { 373 | liq_set_log_callback(local_liq, log_callback_buferred, &buf); 374 | liq_set_log_flush_callback(local_liq, log_callback_buferred_flush, &buf); 375 | opts.log_callback = log_callback_buferred; 376 | opts.log_callback_user_info = &buf; 377 | } 378 | #endif 379 | 380 | 381 | pngquant_error retval = SUCCESS; 382 | 383 | const char *outname = opts.output_file_path; 384 | char *outname_free = NULL; 385 | if (!opts.using_stdout) { 386 | if (!outname) { 387 | outname = outname_free = add_filename_extension(filename, opts.extension); 388 | } 389 | if (!opts.force && file_exists(outname)) { 390 | fprintf(stderr, " error: '%s' exists; not overwriting\n", outname); 391 | retval = NOT_OVERWRITING_ERROR; 392 | } 393 | } 394 | 395 | if (SUCCESS == retval) { 396 | retval = pngquant_file_internal(filename, outname, &opts, local_liq); 397 | } 398 | 399 | free(outname_free); 400 | 401 | liq_attr_destroy(local_liq); 402 | 403 | if (retval) { 404 | #pragma omp critical 405 | { 406 | latest_error = retval; 407 | } 408 | if (retval == TOO_LOW_QUALITY || retval == TOO_LARGE_FILE) { 409 | skipped_count++; 410 | } else { 411 | error_count++; 412 | } 413 | } 414 | ++file_count; 415 | } 416 | 417 | if (error_count) { 418 | verbose_printf(liq, options, "There were errors quantizing %d file%s out of a total of %d file%s.", 419 | error_count, (error_count == 1)? "" : "s", file_count, (file_count == 1)? "" : "s"); 420 | } 421 | if (skipped_count) { 422 | verbose_printf(liq, options, "Skipped %d file%s out of a total of %d file%s.", 423 | skipped_count, (skipped_count == 1)? "" : "s", file_count, (file_count == 1)? "" : "s"); 424 | } 425 | if (!skipped_count && !error_count) { 426 | verbose_printf(liq, options, "Quantized %d image%s.", 427 | file_count, (file_count == 1)? "" : "s"); 428 | } 429 | 430 | if (options->fixed_palette_image) liq_image_destroy(options->fixed_palette_image); 431 | 432 | return latest_error; 433 | } 434 | 435 | /// Don't hack this. Instead use https://github.com/ImageOptim/libimagequant/blob/f54d2f1a3e1cf728e17326f4db0d45811c63f063/example.c 436 | static pngquant_error pngquant_file_internal(const char *filename, const char *outname, struct pngquant_options *options, liq_attr *liq) 437 | { 438 | pngquant_error retval = SUCCESS; 439 | 440 | verbose_printf(liq, options, "%s:", filename); 441 | 442 | liq_image *input_image = NULL; 443 | png24_image input_image_rwpng = {.width=0}; 444 | bool keep_input_pixels = options->skip_if_larger || (options->using_stdout && options->min_quality_limit); // original may need to be output to stdout 445 | if (SUCCESS == retval) { 446 | retval = read_image(liq, filename, options->using_stdin, &input_image_rwpng, &input_image, keep_input_pixels, options->strip, options->verbose); 447 | } 448 | 449 | int quality_percent = 90; // quality on 0-100 scale, updated upon successful remap 450 | png8_image output_image = {.width=0}; 451 | if (SUCCESS == retval) { 452 | verbose_printf(liq, options, " read %luKB file", (input_image_rwpng.file_size+1023UL)/1024UL); 453 | 454 | if (RWPNG_ICCP == input_image_rwpng.input_color) { 455 | verbose_printf(liq, options, " used embedded ICC profile to transform image to sRGB colorspace"); 456 | } else if (RWPNG_GAMA_CHRM == input_image_rwpng.input_color) { 457 | verbose_printf(liq, options, " used gAMA and cHRM chunks to transform image to sRGB colorspace"); 458 | } else if (RWPNG_ICCP_WARN_GRAY == input_image_rwpng.input_color) { 459 | verbose_printf(liq, options, " warning: ignored ICC profile in GRAY colorspace"); 460 | } else if (RWPNG_COCOA == input_image_rwpng.input_color) { 461 | // No comment 462 | } else if (RWPNG_SRGB == input_image_rwpng.input_color) { 463 | verbose_printf(liq, options, " passing sRGB tag from the input"); 464 | } else if (input_image_rwpng.gamma != 0.45455) { 465 | verbose_printf(liq, options, " converted image from gamma %2.1f to gamma 2.2", 466 | 1.0/input_image_rwpng.gamma); 467 | } 468 | 469 | // when using image as source of a fixed palette the palette is extracted using regular quantization 470 | liq_result *remap; 471 | liq_error remap_error = liq_image_quantize(options->fixed_palette_image ? options->fixed_palette_image : input_image, liq, &remap); 472 | 473 | if (LIQ_OK == remap_error) { 474 | 475 | // fixed gamma ~2.2 for the web. PNG can't store exact 1/2.2 476 | // NB: can't change gamma here, because output_color is allowed to be an sRGB tag 477 | liq_set_output_gamma(remap, 0.45455); 478 | liq_set_dithering_level(remap, options->floyd); 479 | 480 | retval = prepare_output_image(remap, input_image, input_image_rwpng.output_color, &output_image); 481 | if (SUCCESS == retval) { 482 | if (LIQ_OK != liq_write_remapped_image_rows(remap, input_image, output_image.row_pointers)) { 483 | retval = OUT_OF_MEMORY_ERROR; 484 | } 485 | 486 | set_palette(remap, &output_image); 487 | 488 | double palette_error = liq_get_quantization_error(remap); 489 | if (palette_error >= 0) { 490 | quality_percent = liq_get_quantization_quality(remap); 491 | verbose_printf(liq, options, " mapped image to new colors...MSE=%.3f (Q=%d)", palette_error, quality_percent); 492 | } 493 | } 494 | liq_result_destroy(remap); 495 | } else if (LIQ_QUALITY_TOO_LOW == remap_error) { 496 | retval = TOO_LOW_QUALITY; 497 | } else { 498 | retval = INVALID_ARGUMENT; // dunno 499 | } 500 | } 501 | 502 | if (SUCCESS == retval) { 503 | 504 | if (options->skip_if_larger) { 505 | // this is very rough approximation, but generally avoid losing more quality than is gained in file size. 506 | // Quality is raised to 1.5, because even greater savings are needed to justify big quality loss. 507 | // but >50% savings are considered always worthwhile in order to allow low quality conversions to work at all 508 | const double quality = quality_percent/100.0; 509 | const double expected_reduced_size = pow(quality, 1.5); 510 | output_image.maximum_file_size = (input_image_rwpng.file_size-1) * (expected_reduced_size < 0.5 ? 0.5 : expected_reduced_size); 511 | } 512 | 513 | output_image.fast_compression = options->fast_compression; 514 | output_image.chunks = input_image_rwpng.chunks; input_image_rwpng.chunks = NULL; 515 | retval = write_image(&output_image, NULL, outname, options, liq); 516 | 517 | if (TOO_LARGE_FILE == retval) { 518 | verbose_printf(liq, options, " file exceeded expected size of %luKB", (unsigned long)output_image.maximum_file_size/1024UL); 519 | } 520 | if (SUCCESS == retval && output_image.metadata_size > 0) { 521 | verbose_printf(liq, options, " copied %dKB of additional PNG metadata", (int)(output_image.metadata_size+999)/1000); 522 | } 523 | } 524 | 525 | if (options->using_stdout && keep_input_pixels && (TOO_LARGE_FILE == retval || TOO_LOW_QUALITY == retval)) { 526 | // when outputting to stdout it'd be nasty to create 0-byte file 527 | // so if quality is too low, output 24-bit original 528 | pngquant_error write_retval = write_image(NULL, &input_image_rwpng, outname, options, liq); 529 | if (write_retval) { 530 | retval = write_retval; 531 | } 532 | } 533 | 534 | if (input_image) liq_image_destroy(input_image); 535 | rwpng_free_image24(&input_image_rwpng); 536 | rwpng_free_image8(&output_image); 537 | 538 | return retval; 539 | } 540 | 541 | static void set_palette(liq_result *result, png8_image *output_image) 542 | { 543 | const liq_palette *palette = liq_get_palette(result); 544 | 545 | output_image->num_palette = palette->count; 546 | for(unsigned int i=0; i < palette->count; i++) { 547 | const liq_color px = palette->entries[i]; 548 | output_image->palette[i] = (rwpng_rgba){.r=px.r, .g=px.g, .b=px.b, .a=px.a}; 549 | } 550 | } 551 | 552 | 553 | static bool file_exists(const char *outname) 554 | { 555 | FILE *outfile = fopen(outname, "rb"); 556 | if ((outfile ) != NULL) { 557 | fclose(outfile); 558 | return true; 559 | } 560 | return false; 561 | } 562 | 563 | /* build the output filename from the input name by inserting "-fs8" or 564 | * "-or8" before the ".png" extension (or by appending that plus ".png" if 565 | * there isn't any extension), then make sure it doesn't exist already */ 566 | static char *add_filename_extension(const char *filename, const char *newext) 567 | { 568 | size_t x = strlen(filename); 569 | 570 | char* outname = malloc(x+4+strlen(newext)+1); 571 | if (!outname) return NULL; 572 | 573 | strcpy(outname, filename); 574 | if (x > 4 && (strncmp(outname+x-4, ".png", 4) == 0 || strncmp(outname+x-4, ".PNG", 4) == 0)) { 575 | strcpy(outname+x-4, newext); 576 | } else { 577 | strcpy(outname+x, newext); 578 | } 579 | 580 | return outname; 581 | } 582 | 583 | static char *temp_filename(const char *basename) { 584 | size_t x = strlen(basename); 585 | 586 | char *outname = malloc(x+1+4); 587 | if (!outname) return NULL; 588 | 589 | strcpy(outname, basename); 590 | strcpy(outname+x, ".tmp"); 591 | 592 | return outname; 593 | } 594 | 595 | static void set_binary_mode(FILE *fp) 596 | { 597 | #if defined(_WIN32) || defined(WIN32) || defined(__WIN32__) 598 | setmode(fp == stdout ? 1 : 0, O_BINARY); 599 | #endif 600 | } 601 | 602 | static const char *filename_part(const char *path) 603 | { 604 | const char *outfilename = strrchr(path, '/'); 605 | if (outfilename) { 606 | return outfilename+1; 607 | } else { 608 | return path; 609 | } 610 | } 611 | 612 | static bool replace_file(const char *from, const char *to, const bool force) { 613 | #if defined(_WIN32) || defined(WIN32) || defined(__WIN32__) 614 | if (force) { 615 | // On Windows rename doesn't replace 616 | unlink(to); 617 | } 618 | #endif 619 | return (0 == rename(from, to)); 620 | } 621 | 622 | static pngquant_error write_image(png8_image *output_image, png24_image *output_image24, const char *outname, struct pngquant_options *options, liq_attr *liq) 623 | { 624 | FILE *outfile; 625 | char *tempname = NULL; 626 | 627 | if (options->using_stdout) { 628 | set_binary_mode(stdout); 629 | outfile = stdout; 630 | 631 | if (output_image) { 632 | verbose_printf(liq, options, " writing %d-color image to stdout", output_image->num_palette); 633 | } else { 634 | verbose_printf(liq, options, " writing truecolor image to stdout"); 635 | } 636 | } else { 637 | tempname = temp_filename(outname); 638 | if (!tempname) return OUT_OF_MEMORY_ERROR; 639 | 640 | if ((outfile = fopen(tempname, "wb")) == NULL) { 641 | fprintf(stderr, " error: cannot open '%s' for writing\n", tempname); 642 | free(tempname); 643 | return CANT_WRITE_ERROR; 644 | } 645 | 646 | if (output_image) { 647 | verbose_printf(liq, options, " writing %d-color image as %s", output_image->num_palette, filename_part(outname)); 648 | } else { 649 | verbose_printf(liq, options, " writing truecolor image as %s", filename_part(outname)); 650 | } 651 | } 652 | 653 | pngquant_error retval; 654 | #pragma omp critical (libpng) 655 | { 656 | if (output_image) { 657 | retval = rwpng_write_image8(outfile, output_image); 658 | } else { 659 | retval = rwpng_write_image24(outfile, output_image24); 660 | } 661 | } 662 | 663 | if (!options->using_stdout) { 664 | fclose(outfile); 665 | 666 | if (SUCCESS == retval) { 667 | // Image has been written to a temporary file and then moved over destination. 668 | // This makes replacement atomic and avoids damaging destination file on write error. 669 | if (!replace_file(tempname, outname, options->force)) { 670 | retval = CANT_WRITE_ERROR; 671 | } 672 | } 673 | 674 | if (retval) { 675 | unlink(tempname); 676 | } 677 | } 678 | free(tempname); 679 | 680 | if (retval && retval != TOO_LARGE_FILE) { 681 | fprintf(stderr, " error: failed writing image to %s (%d)\n", options->using_stdout ? "stdout" : outname, retval); 682 | } 683 | 684 | return retval; 685 | } 686 | 687 | static pngquant_error read_image(liq_attr *options, const char *filename, int using_stdin, png24_image *input_image_p, liq_image **liq_image_p, bool keep_input_pixels, bool strip, bool verbose) 688 | { 689 | FILE *infile; 690 | 691 | if (using_stdin) { 692 | set_binary_mode(stdin); 693 | infile = stdin; 694 | } else if ((infile = fopen(filename, "rb")) == NULL) { 695 | fprintf(stderr, " error: cannot open %s for reading\n", filename); 696 | return READ_ERROR; 697 | } 698 | 699 | pngquant_error retval; 700 | #pragma omp critical (libpng) 701 | { 702 | retval = rwpng_read_image24(infile, input_image_p, strip, verbose); 703 | } 704 | 705 | if (!using_stdin) { 706 | fclose(infile); 707 | } 708 | 709 | if (retval) { 710 | fprintf(stderr, " error: cannot decode image %s\n", using_stdin ? "from stdin" : filename_part(filename)); 711 | return retval; 712 | } 713 | 714 | *liq_image_p = liq_image_create_rgba_rows(options, (void**)input_image_p->row_pointers, input_image_p->width, input_image_p->height, input_image_p->gamma); 715 | 716 | if (!*liq_image_p) { 717 | return OUT_OF_MEMORY_ERROR; 718 | } 719 | 720 | if (!keep_input_pixels) { 721 | if (LIQ_OK != liq_image_set_memory_ownership(*liq_image_p, LIQ_OWN_ROWS | LIQ_OWN_PIXELS)) { 722 | return OUT_OF_MEMORY_ERROR; 723 | } 724 | input_image_p->row_pointers = NULL; 725 | input_image_p->rgba_data = NULL; 726 | } 727 | 728 | return SUCCESS; 729 | } 730 | 731 | static pngquant_error prepare_output_image(liq_result *result, liq_image *input_image, rwpng_color_transform output_color, png8_image *output_image) 732 | { 733 | output_image->width = liq_image_get_width(input_image); 734 | output_image->height = liq_image_get_height(input_image); 735 | output_image->gamma = liq_get_output_gamma(result); 736 | output_image->output_color = output_color; 737 | 738 | /* 739 | ** Step 3.7 [GRR]: allocate memory for the entire indexed image 740 | */ 741 | 742 | output_image->indexed_data = malloc((size_t)output_image->height * (size_t)output_image->width); 743 | output_image->row_pointers = malloc((size_t)output_image->height * sizeof(output_image->row_pointers[0])); 744 | 745 | if (!output_image->indexed_data || !output_image->row_pointers) { 746 | return OUT_OF_MEMORY_ERROR; 747 | } 748 | 749 | for(size_t row = 0; row < output_image->height; row++) { 750 | output_image->row_pointers[row] = output_image->indexed_data + row * output_image->width; 751 | } 752 | 753 | const liq_palette *palette = liq_get_palette(result); 754 | // tRNS, etc. 755 | output_image->num_palette = palette->count; 756 | 757 | return SUCCESS; 758 | } 759 | -------------------------------------------------------------------------------- /pngquant.xcodeproj/project.pbxproj: -------------------------------------------------------------------------------- 1 | // !$*UTF8*$! 2 | { 3 | /* generated with cargo-xcode 1.8.2 */ 4 | archiveVersion = 1; 5 | classes = { 6 | }; 7 | objectVersion = 53; 8 | objects = { 9 | 10 | /* Begin PBXBuildFile section */ 11 | CA00FD3D7ED13B3B3D19E325 /* Cargo.toml in Sources */ = {isa = PBXBuildFile; fileRef = CAF971CC4B513EF4668187A5 /* Cargo.toml */; settings = {COMPILER_FLAGS = "--bin 'pngquant' --no-default-features"; }; }; 12 | 13 | /* End PBXBuildFile section */ 14 | 15 | /* Begin PBXBuildRule section */ 16 | CAF471CC4B51AC6C1400ACA8 /* PBXBuildRule */ = { 17 | isa = PBXBuildRule; 18 | compilerSpec = com.apple.compilers.proxy.script; 19 | dependencyFile = "$(DERIVED_FILE_DIR)/$(CARGO_XCODE_TARGET_ARCH)-$(EXECUTABLE_NAME).d"; 20 | filePatterns = "*/Cargo.toml"; 21 | fileType = pattern.proxy; 22 | inputFiles = ( 23 | ); 24 | isEditable = 0; 25 | name = "Cargo project build"; 26 | outputFiles = ( 27 | "$(OBJECT_FILE_DIR)/$(CARGO_XCODE_TARGET_ARCH)-$(EXECUTABLE_NAME)", 28 | ); 29 | script = "# generated with cargo-xcode 1.8.2\nset -xeu;\nexport PATH=\"$HOME/.cargo/bin:$PATH:/usr/local/bin:/opt/homebrew/bin\";\n# don't use ios/watchos linker for build scripts and proc macros\nexport CARGO_TARGET_AARCH64_APPLE_DARWIN_LINKER=/usr/bin/ld\nexport CARGO_TARGET_X86_64_APPLE_DARWIN_LINKER=/usr/bin/ld\n\nif [ \"${IS_MACCATALYST-NO}\" = YES ]; then\n CARGO_XCODE_TARGET_OS=ios-macabi\nfi\nCARGO_XCODE_TARGET_TRIPLE=\"${CARGO_XCODE_TARGET_ARCH}-apple-${CARGO_XCODE_TARGET_OS}\"\n\nif [ \"$CARGO_XCODE_BUILD_PROFILE\" == release ]; then\n OTHER_INPUT_FILE_FLAGS=\"${OTHER_INPUT_FILE_FLAGS} --release\"\nfi\n\nif [ \"$ACTION\" = clean ]; then\n cargo clean --verbose --manifest-path=\"$SCRIPT_INPUT_FILE\" ${OTHER_INPUT_FILE_FLAGS} --target=\"${CARGO_XCODE_TARGET_TRIPLE}\";\n rm -f \"$SCRIPT_OUTPUT_FILE_0\"\n exit 0\nfi\ncargo build --verbose --manifest-path=\"$SCRIPT_INPUT_FILE\" --features=\"${CARGO_XCODE_FEATURES:-}\" ${OTHER_INPUT_FILE_FLAGS} --target=\"${CARGO_XCODE_TARGET_TRIPLE}\" || {\n if command -v rustup &> /dev/null; then\n if ! rustup target list --installed | grep -Eq \"${CARGO_XCODE_TARGET_TRIPLE}\"; then\n echo >&2 \"warning: this build requires rustup toolchain for $CARGO_XCODE_TARGET_TRIPLE, but it isn't installed (will try rustup next)\"\n rustup target add \"${CARGO_XCODE_TARGET_TRIPLE}\" || echo >&2 \"warning: can't install $CARGO_XCODE_TARGET_TRIPLE\"\n fi\n fi\n echo >&2 \"error: cargo build failed\"; exit 1; }\n\n# it's too hard to explain Cargo's actual exe path to Xcode build graph, so hardlink to a known-good path instead\nBUILT_SRC=\"${CARGO_TARGET_DIR}/${CARGO_XCODE_TARGET_TRIPLE}/${CARGO_XCODE_BUILD_PROFILE}/${CARGO_XCODE_CARGO_FILE_NAME}\"\nln -f -- \"$BUILT_SRC\" \"$SCRIPT_OUTPUT_FILE_0\" || { echo >&2 \"can't hardlink $BUILT_SRC to $SCRIPT_OUTPUT_FILE_0\"; exit 1; }\n\n# cargo generates a dep file, but for its own path, so append our rename to it\nDEP_FILE_SRC=\"${CARGO_TARGET_DIR}/${CARGO_XCODE_TARGET_TRIPLE}/${CARGO_XCODE_BUILD_PROFILE}/${CARGO_XCODE_CARGO_DEP_FILE_NAME}\"\nif [ -f \"$DEP_FILE_SRC\" ]; then\n DEP_FILE_DST=\"${DERIVED_FILE_DIR}/${CARGO_XCODE_TARGET_ARCH}-${EXECUTABLE_NAME}.d\"\n cp -f \"$DEP_FILE_SRC\" \"$DEP_FILE_DST\" || { echo >&2 \"can't copy $DEP_FILE_SRC to $DEP_FILE_DST\"; exit 1; }\n\n echo >> \"$DEP_FILE_DST\" \"${SCRIPT_OUTPUT_FILE_0/ /\\\\ /}: ${BUILT_SRC/ /\\\\ /}\"\nfi\n\n# lipo script needs to know all the platform-specific files that have been built\n# archs is in the file name, so that paths don't stay around after archs change\n# must match input for LipoScript\nFILE_LIST=\"${DERIVED_FILE_DIR}/${ARCHS}-${EXECUTABLE_NAME}.xcfilelist\"\ntouch \"$FILE_LIST\"\nif ! grep -Eq \"$SCRIPT_OUTPUT_FILE_0\" \"$FILE_LIST\" ; then\n echo >> \"$FILE_LIST\" \"$SCRIPT_OUTPUT_FILE_0\"\nfi\n\necho \"success: $ACTION of $SCRIPT_OUTPUT_FILE_0 for $CARGO_XCODE_TARGET_TRIPLE\"\n"; 30 | }; 31 | /* End PBXBuildRule section */ 32 | 33 | /* Begin PBXFileReference section */ 34 | CA008FFA42538780035A8A54 /* pngquant */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = pngquant; sourceTree = BUILT_PRODUCTS_DIR; }; 35 | CAF971CC4B513EF4668187A5 /* Cargo.toml */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = Cargo.toml; sourceTree = ""; }; 36 | 37 | /* End PBXFileReference section */ 38 | 39 | /* Begin PBXGroup section */ 40 | CAF071CC4B51D65BC3C892A8 = { 41 | isa = PBXGroup; 42 | children = ( 43 | CAF971CC4B513EF4668187A5 /* Cargo.toml */, 44 | CAF171CC4B5122869D176AE5 /* Products */, 45 | CAF271CC4B5198AF0B5890DB /* Frameworks */, 46 | ); 47 | sourceTree = ""; 48 | }; 49 | CAF171CC4B5122869D176AE5 /* Products */ = { 50 | isa = PBXGroup; 51 | children = ( 52 | CA008FFA42538780035A8A54 /* pngquant */, 53 | ); 54 | name = Products; 55 | sourceTree = ""; 56 | }; 57 | CAF271CC4B5198AF0B5890DB /* Frameworks */ = { 58 | isa = PBXGroup; 59 | children = ( 60 | ); 61 | name = Frameworks; 62 | sourceTree = ""; 63 | }; 64 | /* End PBXGroup section */ 65 | 66 | /* Begin PBXNativeTarget section */ 67 | CA008FFA42533B3B3D19E325 /* pngquant-bin */ = { 68 | isa = PBXNativeTarget; 69 | buildConfigurationList = CA00C6FFFF673B3B3D19E325 /* Build configuration list for PBXNativeTarget "pngquant-bin" */; 70 | buildPhases = ( 71 | CA005B305E043B3B3D19E325 /* Sources */, 72 | CAF571CC4B51AF6EBB7F357C /* Universal Binary lipo */, 73 | ); 74 | buildRules = ( 75 | CAF471CC4B51AC6C1400ACA8 /* PBXBuildRule */, 76 | ); 77 | dependencies = ( 78 | ); 79 | name = "pngquant-bin"; 80 | productName = pngquant; 81 | productReference = CA008FFA42538780035A8A54 /* pngquant */; 82 | productType = "com.apple.product-type.tool"; 83 | }; 84 | /* End PBXNativeTarget section */ 85 | 86 | /* Begin PBXProject section */ 87 | CAF371CC4B51E04653AD465F /* Project object */ = { 88 | isa = PBXProject; 89 | attributes = { 90 | LastUpgradeCheck = 1500; 91 | TargetAttributes = { 92 | CA008FFA42533B3B3D19E325 = { 93 | CreatedOnToolsVersion = 9.2; 94 | ProvisioningStyle = Automatic; 95 | }; 96 | }; 97 | }; 98 | buildConfigurationList = CAF671CC4B5180E02D6C7F57 /* Build configuration list for PBXProject "pngquant" */; 99 | compatibilityVersion = "Xcode 11.4"; 100 | developmentRegion = en; 101 | hasScannedForEncodings = 0; 102 | knownRegions = ( 103 | en, 104 | Base, 105 | ); 106 | mainGroup = CAF071CC4B51D65BC3C892A8; 107 | productRefGroup = CAF171CC4B5122869D176AE5 /* Products */; 108 | projectDirPath = ""; 109 | projectRoot = ""; 110 | targets = ( 111 | CA008FFA42533B3B3D19E325 /* pngquant-bin */, 112 | ); 113 | }; 114 | /* End PBXProject section */ 115 | 116 | /* Begin PBXShellScriptBuildPhase section */ 117 | CAF571CC4B51AF6EBB7F357C /* Universal Binary lipo */ = { 118 | isa = PBXShellScriptBuildPhase; 119 | buildActionMask = 2147483647; 120 | files = ( 121 | ); 122 | inputFileListPaths = ( 123 | ); 124 | inputPaths = ( 125 | "$(DERIVED_FILE_DIR)/$(ARCHS)-$(EXECUTABLE_NAME).xcfilelist", 126 | ); 127 | name = "Universal Binary lipo"; 128 | outputFileListPaths = ( 129 | ); 130 | outputPaths = ( 131 | "$(TARGET_BUILD_DIR)/$(EXECUTABLE_PATH)", 132 | ); 133 | runOnlyForDeploymentPostprocessing = 0; 134 | shellPath = /bin/sh; 135 | shellScript = "# generated with cargo-xcode 1.8.2\nset -eux;\ntr '\\n' '\\0' < \"$DERIVED_FILE_DIR/$ARCHS-$EXECUTABLE_NAME.xcfilelist\" | xargs -0 lipo -create -output \"$TARGET_BUILD_DIR/$EXECUTABLE_PATH\"\nif [ ${LD_DYLIB_INSTALL_NAME:+1} ]; then\n install_name_tool -id \"$LD_DYLIB_INSTALL_NAME\" \"$TARGET_BUILD_DIR/$EXECUTABLE_PATH\"\nfi\n"; 136 | }; 137 | /* End PBXShellScriptBuildPhase section */ 138 | 139 | /* Begin PBXSourcesBuildPhase section */ 140 | CA005B305E043B3B3D19E325 /* Sources */ = { 141 | isa = PBXSourcesBuildPhase; 142 | buildActionMask = 2147483647; 143 | files = ( 144 | CA00FD3D7ED13B3B3D19E325 /* Cargo.toml in Sources */, 145 | ); 146 | runOnlyForDeploymentPostprocessing = 0; 147 | }; 148 | 149 | /* End PBXSourcesBuildPhase section */ 150 | 151 | /* Begin XCBuildConfiguration section */ 152 | CA003B5FE0C83B3B3D19E325 /* Release */ = { 153 | isa = XCBuildConfiguration; 154 | buildSettings = { 155 | CARGO_XCODE_CARGO_DEP_FILE_NAME = pngquant.d; 156 | CARGO_XCODE_CARGO_FILE_NAME = pngquant; 157 | 158 | PRODUCT_NAME = pngquant; 159 | SUPPORTED_PLATFORMS = macosx; 160 | 161 | }; 162 | name = Release; 163 | }; 164 | CA009AA08B823B3B3D19E325 /* Debug */ = { 165 | isa = XCBuildConfiguration; 166 | buildSettings = { 167 | CARGO_XCODE_CARGO_DEP_FILE_NAME = pngquant.d; 168 | CARGO_XCODE_CARGO_FILE_NAME = pngquant; 169 | 170 | PRODUCT_NAME = pngquant; 171 | SUPPORTED_PLATFORMS = macosx; 172 | 173 | }; 174 | name = Debug; 175 | }; 176 | 177 | CAF76179D3823CC16B37690B /* Release */ = { 178 | isa = XCBuildConfiguration; 179 | buildSettings = { 180 | ADDITIONAL_SDKS = macosx; 181 | ALWAYS_SEARCH_USER_PATHS = NO; 182 | CARGO_TARGET_DIR = "$(PROJECT_TEMP_DIR)/cargo_target"; 183 | CARGO_XCODE_BUILD_PROFILE = release; 184 | CARGO_XCODE_FEATURES = "static,cocoa"; 185 | CARGO_XCODE_TARGET_ARCH = "$(CURRENT_ARCH)"; 186 | "CARGO_XCODE_TARGET_ARCH[arch=arm64]" = aarch64; 187 | "CARGO_XCODE_TARGET_ARCH[arch=arm64e]" = aarch64; 188 | "CARGO_XCODE_TARGET_ARCH[arch=i386]" = i686; 189 | "CARGO_XCODE_TARGET_ARCH[arch=x86_64h]" = x86_64; 190 | CARGO_XCODE_TARGET_OS = "$(PLATFORM_NAME)"; 191 | "CARGO_XCODE_TARGET_OS[sdk=appletvos]" = tvos; 192 | "CARGO_XCODE_TARGET_OS[sdk=appletvsimulator]" = tvos; 193 | "CARGO_XCODE_TARGET_OS[sdk=iphoneos]" = ios; 194 | "CARGO_XCODE_TARGET_OS[sdk=iphonesimulator]" = "ios-sim"; 195 | "CARGO_XCODE_TARGET_OS[sdk=iphonesimulator][arch=x86_64]" = ios; 196 | "CARGO_XCODE_TARGET_OS[sdk=macosx*]" = darwin; 197 | "CARGO_XCODE_TARGET_OS[sdk=watchsimulator]" = "watchos-sim"; 198 | CURRENT_PROJECT_VERSION = 3.0; 199 | MARKETING_VERSION = 3.0.2; 200 | PRODUCT_NAME = pngquant; 201 | RUSTUP_TOOLCHAIN = ""; 202 | SDKROOT = macosx; 203 | SUPPORTS_MACCATALYST = YES; 204 | }; 205 | name = Release; 206 | }; 207 | CAF86179D382228BE02872F8 /* Debug */ = { 208 | isa = XCBuildConfiguration; 209 | buildSettings = { 210 | ADDITIONAL_SDKS = macosx; 211 | ALWAYS_SEARCH_USER_PATHS = NO; 212 | CARGO_TARGET_DIR = "$(PROJECT_TEMP_DIR)/cargo_target"; 213 | CARGO_XCODE_BUILD_PROFILE = debug; 214 | CARGO_XCODE_FEATURES = "static,cocoa"; 215 | CARGO_XCODE_TARGET_ARCH = "$(CURRENT_ARCH)"; 216 | "CARGO_XCODE_TARGET_ARCH[arch=arm64]" = aarch64; 217 | "CARGO_XCODE_TARGET_ARCH[arch=arm64e]" = aarch64; 218 | "CARGO_XCODE_TARGET_ARCH[arch=i386]" = i686; 219 | "CARGO_XCODE_TARGET_ARCH[arch=x86_64h]" = x86_64; 220 | CARGO_XCODE_TARGET_OS = "$(PLATFORM_NAME)"; 221 | "CARGO_XCODE_TARGET_OS[sdk=appletvos]" = tvos; 222 | "CARGO_XCODE_TARGET_OS[sdk=appletvsimulator]" = tvos; 223 | "CARGO_XCODE_TARGET_OS[sdk=iphoneos]" = ios; 224 | "CARGO_XCODE_TARGET_OS[sdk=iphonesimulator]" = "ios-sim"; 225 | "CARGO_XCODE_TARGET_OS[sdk=iphonesimulator][arch=x86_64]" = ios; 226 | "CARGO_XCODE_TARGET_OS[sdk=macosx*]" = darwin; 227 | "CARGO_XCODE_TARGET_OS[sdk=watchsimulator]" = "watchos-sim"; 228 | CURRENT_PROJECT_VERSION = 3.0; 229 | MARKETING_VERSION = 3.0.2; 230 | ONLY_ACTIVE_ARCH = YES; 231 | PRODUCT_NAME = pngquant; 232 | RUSTUP_TOOLCHAIN = ""; 233 | SDKROOT = macosx; 234 | SUPPORTS_MACCATALYST = YES; 235 | }; 236 | name = Debug; 237 | }; 238 | /* End XCBuildConfiguration section */ 239 | 240 | /* Begin XCConfigurationList section */ 241 | CA00C6FFFF673B3B3D19E325 /* Build configuration list for PBXNativeTarget "pngquant-bin" */ = { 242 | isa = XCConfigurationList; 243 | buildConfigurations = ( 244 | CA003B5FE0C83B3B3D19E325 /* Release */, 245 | CA009AA08B823B3B3D19E325 /* Debug */, 246 | ); 247 | defaultConfigurationIsVisible = 0; 248 | defaultConfigurationName = Release; 249 | }; 250 | 251 | CAF671CC4B5180E02D6C7F57 /* Build configuration list for PBXProject "pngquant" */ = { 252 | isa = XCConfigurationList; 253 | buildConfigurations = ( 254 | CAF76179D3823CC16B37690B /* Release */, 255 | CAF86179D382228BE02872F8 /* Debug */, 256 | ); 257 | defaultConfigurationIsVisible = 0; 258 | defaultConfigurationName = Release; 259 | }; 260 | /* End XCConfigurationList section */ 261 | }; 262 | rootObject = CAF371CC4B51E04653AD465F /* Project object */; 263 | } 264 | -------------------------------------------------------------------------------- /pngquant_opts.c: -------------------------------------------------------------------------------- 1 | /* 2 | ** © 2017 by Kornel Lesiński. 3 | ** 4 | ** See COPYRIGHT file for license. 5 | */ 6 | 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | #include "rwpng.h" 14 | #include "libimagequant.h" /* if you get compile error, add -Ilib to compiler flags */ 15 | #include "pngquant_opts.h" 16 | 17 | extern char *optarg; 18 | extern int optind, opterr; 19 | 20 | static const struct {const char *old; const char *newopt;} obsolete_options[] = { 21 | {"-fs","--floyd=1"}, 22 | {"-nofs", "--ordered"}, 23 | {"-floyd", "--floyd=1"}, 24 | {"-nofloyd", "--ordered"}, 25 | {"-ordered", "--ordered"}, 26 | {"-force", "--force"}, 27 | {"-noforce", "--no-force"}, 28 | {"-verbose", "--verbose"}, 29 | {"-quiet", "--quiet"}, 30 | {"-noverbose", "--quiet"}, 31 | {"-noquiet", "--verbose"}, 32 | {"-help", "--help"}, 33 | {"-version", "--version"}, 34 | {"-ext", "--ext"}, 35 | {"-speed", "--speed"}, 36 | }; 37 | 38 | static void fix_obsolete_options(const unsigned int argc, char *argv[]) 39 | { 40 | for(unsigned int argn=1; argn < argc; argn++) { 41 | if ('-' != argv[argn][0]) continue; 42 | 43 | if ('-' == argv[argn][1]) break; // stop on first --option or -- 44 | 45 | for(unsigned int i=0; i < sizeof(obsolete_options)/sizeof(obsolete_options[0]); i++) { 46 | if (0 == strcmp(obsolete_options[i].old, argv[argn])) { 47 | fprintf(stderr, " warning: option '%s' has been replaced with '%s'.\n", obsolete_options[i].old, obsolete_options[i].newopt); 48 | argv[argn] = (char*)obsolete_options[i].newopt; 49 | } 50 | } 51 | } 52 | } 53 | 54 | enum {arg_floyd=1, arg_ordered, arg_ext, arg_no_force, arg_iebug, 55 | arg_transbug, arg_map, arg_posterize, arg_skip_larger, arg_strip}; 56 | 57 | static const struct option long_options[] = { 58 | {"verbose", no_argument, NULL, 'v'}, 59 | {"quiet", no_argument, NULL, 'q'}, 60 | {"force", no_argument, NULL, 'f'}, 61 | {"no-force", no_argument, NULL, arg_no_force}, 62 | {"floyd", optional_argument, NULL, arg_floyd}, 63 | {"ordered", no_argument, NULL, arg_ordered}, 64 | {"nofs", no_argument, NULL, arg_ordered}, 65 | {"iebug", no_argument, NULL, arg_iebug}, 66 | {"transbug", no_argument, NULL, arg_transbug}, 67 | {"ext", required_argument, NULL, arg_ext}, 68 | {"skip-if-larger", no_argument, NULL, arg_skip_larger}, 69 | {"output", required_argument, NULL, 'o'}, 70 | {"speed", required_argument, NULL, 's'}, 71 | {"quality", required_argument, NULL, 'Q'}, 72 | {"posterize", required_argument, NULL, arg_posterize}, 73 | {"strip", no_argument, NULL, arg_strip}, 74 | {"map", required_argument, NULL, arg_map}, 75 | {"version", no_argument, NULL, 'V'}, 76 | {"help", no_argument, NULL, 'h'}, 77 | {NULL, 0, NULL, 0}, 78 | }; 79 | 80 | pngquant_error pngquant_parse_options(int argc, char *argv[], struct pngquant_options *options) 81 | { 82 | fix_obsolete_options(argc, argv); 83 | 84 | int opt; 85 | do { 86 | opt = getopt_long(argc, argv, "Vvqfhs:Q:o:", long_options, NULL); 87 | switch (opt) { 88 | case 'v': 89 | options->verbose = true; 90 | break; 91 | case 'q': 92 | options->verbose = false; 93 | break; 94 | 95 | case arg_floyd: 96 | options->floyd = optarg ? atof(optarg) : 1.f; 97 | if (options->floyd < 0 || options->floyd > 1.f) { 98 | fputs("--floyd argument must be in 0..1 range\n", stderr); 99 | return INVALID_ARGUMENT; 100 | } 101 | break; 102 | case arg_ordered: options->floyd = 0; break; 103 | 104 | case 'f': options->force = true; break; 105 | case arg_no_force: options->force = false; break; 106 | 107 | case arg_ext: options->extension = optarg; break; 108 | case 'o': 109 | if (options->output_file_path) { 110 | fputs("--output option can be used only once\n", stderr); 111 | return INVALID_ARGUMENT; 112 | } 113 | if (strcmp(optarg, "-") == 0) { 114 | options->using_stdout = true; 115 | break; 116 | } 117 | options->output_file_path = optarg; break; 118 | 119 | case arg_iebug: 120 | options->iebug = true; 121 | break; 122 | 123 | case arg_transbug: 124 | options->last_index_transparent = true; 125 | break; 126 | 127 | case arg_skip_larger: 128 | options->skip_if_larger = true; 129 | break; 130 | 131 | case 's': 132 | options->speed = optarg[0] == '0' ? -1 : atoi(optarg); 133 | break; 134 | 135 | case 'Q': 136 | options->quality = optarg; 137 | break; 138 | 139 | case arg_posterize: 140 | options->posterize = atoi(optarg); 141 | break; 142 | 143 | case arg_strip: 144 | options->strip = true; 145 | break; 146 | 147 | case arg_map: 148 | options->map_file = optarg; 149 | break; 150 | 151 | case 'h': 152 | options->print_help = true; 153 | break; 154 | 155 | case 'V': 156 | options->print_version = true; 157 | break; 158 | 159 | case -1: break; 160 | 161 | default: 162 | return INVALID_ARGUMENT; 163 | } 164 | } while (opt != -1); 165 | 166 | int argn = optind; 167 | 168 | if (argn < argc) { 169 | char *colors_end; 170 | unsigned long colors = strtoul(argv[argn], &colors_end, 10); 171 | if (colors_end != argv[argn] && '\0' == colors_end[0]) { 172 | options->colors = colors; 173 | argn++; 174 | } 175 | 176 | if (argn == argc || (argn == argc-1 && 0==strcmp(argv[argn],"-"))) { 177 | options->using_stdin = true; 178 | options->using_stdout = !options->output_file_path; 179 | argn = argc-1; 180 | } 181 | 182 | options->num_files = argc-argn; 183 | options->files = argv+argn; 184 | } else if (argn <= 1) { 185 | options->missing_arguments = true; 186 | } 187 | 188 | return SUCCESS; 189 | } 190 | -------------------------------------------------------------------------------- /pngquant_opts.h: -------------------------------------------------------------------------------- 1 | #ifndef PNGQUANT_OPTS_H 2 | #define PNGQUANT_OPTS_H 3 | 4 | struct pngquant_options { 5 | liq_image *fixed_palette_image; 6 | liq_log_callback_function *log_callback; 7 | void *log_callback_user_info; 8 | const char *quality; 9 | const char *extension; 10 | const char *output_file_path; 11 | const char *map_file; 12 | char *const *files; 13 | unsigned int num_files; 14 | unsigned int colors; 15 | unsigned int speed; 16 | unsigned int posterize; 17 | float floyd; 18 | bool using_stdin, using_stdout, force, fast_compression, 19 | min_quality_limit, skip_if_larger, 20 | strip, iebug, last_index_transparent, 21 | print_help, print_version, missing_arguments, 22 | verbose; 23 | }; 24 | 25 | pngquant_error pngquant_parse_options(int argc, char *argv[], struct pngquant_options *options); 26 | #endif 27 | -------------------------------------------------------------------------------- /rust/bin.rs: -------------------------------------------------------------------------------- 1 | /* 2 | ** © 2019 by Kornel Lesiński. 3 | ** 4 | ** See COPYRIGHT file for license. 5 | */ 6 | 7 | extern crate libpng_sys; 8 | 9 | #[cfg(feature = "cocoa")] 10 | pub mod rwpng_cocoa; 11 | 12 | #[cfg(feature = "lcms2")] 13 | extern crate lcms2_sys; 14 | use imagequant_sys::liq_error::LIQ_OK; 15 | use imagequant_sys::*; 16 | use libc::FILE; 17 | use crate::ffi::pngquant_internal_print_config; 18 | use std::os::raw::{c_uint, c_char}; 19 | 20 | use std::ptr; 21 | use std::io; 22 | use std::ffi::{CString, CStr}; 23 | 24 | mod ffi; 25 | use crate::ffi::*; 26 | use crate::ffi::pngquant_error::*; 27 | 28 | fn unwrap_ptr(opt: Option<&CString>) -> *const c_char { 29 | opt.map_or(ptr::null(), |c| c.as_ptr()) 30 | } 31 | 32 | fn print_full_version(fd: &mut dyn io::Write, c_fd: *mut FILE) { 33 | let _ = writeln!(fd, "pngquant, {} (Rust), by Kornel Lesinski, Greg Roelofs.", env!("CARGO_PKG_VERSION")); 34 | let _ = fd.flush(); 35 | unsafe{pngquant_internal_print_config(c_fd);} 36 | let _ = writeln!(fd); 37 | } 38 | 39 | fn print_usage(fd: &mut dyn io::Write) { 40 | let _ = writeln!(fd, "{}", unsafe { CStr::from_ptr(PNGQUANT_USAGE) }.to_str().unwrap()); 41 | } 42 | 43 | /** 44 | * N = automatic quality, uses limit unless force is set (N-N or 0-N) 45 | * -N = no better than N (same as 0-N) 46 | * N-M = no worse than N, no better than M 47 | * N- = no worse than N, perfect if possible (same as N-100) 48 | * 49 | * where N,M are numbers between 0 (lousy) and 100 (perfect) 50 | */ 51 | fn parse_quality(quality: &str) -> Option<(u8, u8)> { 52 | let mut parts = quality.splitn(2, '-'); 53 | let left = parts.next().unwrap(); 54 | let right = parts.next(); 55 | 56 | Some(match (left, right) { 57 | // quality="%d-" 58 | (t, Some("")) => { 59 | (t.parse().ok()?, 100) 60 | }, 61 | // quality="-%d" 62 | ("", Some(t)) => { 63 | (0, t.parse().ok()?) 64 | }, 65 | // quality="%d" 66 | (t, None) => { 67 | let target = t.parse().ok()?; 68 | ((u16::from(target)*9/10) as u8, target) 69 | }, 70 | // quality="%d-%d" 71 | (l, Some(t)) => { 72 | (l.parse().ok()?, t.parse().ok()?) 73 | }, 74 | }) 75 | } 76 | 77 | unsafe extern "C" fn log_callback(_a: &liq_attr, msg: *const c_char, _user: AnySyncSendPtr) { 78 | println!("{}", CStr::from_ptr(msg).to_str().unwrap()); 79 | } 80 | 81 | fn main() { 82 | std::process::exit(run() as _); 83 | } 84 | 85 | fn run() -> ffi::pngquant_error { 86 | let mut opts = getopts::Options::new(); 87 | 88 | opts.optflag("v", "verbose", ""); 89 | opts.optflag("h", "help", ""); 90 | opts.optflag("q", "quiet", ""); 91 | opts.optflag("f", "force", ""); 92 | opts.optflag("", "no-force", ""); 93 | opts.optflag("", "ordered", ""); 94 | opts.optflag("", "nofs", ""); 95 | opts.optflag("", "iebug", ""); 96 | opts.optflag("", "transbug", ""); 97 | opts.optflag("", "skip-if-larger", ""); 98 | opts.optflag("", "strip", ""); 99 | opts.optflag("V", "version", ""); 100 | opts.optflagopt("", "floyd", "0.0-1.0", ""); 101 | opts.optopt("", "ext", "extension", ""); 102 | opts.optopt("o", "output", "file", ""); 103 | opts.optopt("s", "speed", "4", ""); 104 | opts.optopt("Q", "quality", "0-100", ""); 105 | opts.optopt("", "posterize", "0", ""); 106 | opts.optopt("", "map", "png", ""); 107 | opts.optopt("", "colors", "0", ""); 108 | 109 | let args: Vec<_> = wild::args().skip(1).collect(); 110 | let has_some_explicit_args = !args.is_empty(); 111 | let mut m = match opts.parse(args) { 112 | Ok(m) => m, 113 | Err(err) => { 114 | eprintln!("{err}"); 115 | print_usage(&mut io::stderr()); 116 | return MISSING_ARGUMENT; 117 | }, 118 | }; 119 | 120 | let posterize = m.opt_str("posterize").and_then(|p| p.parse().ok()).unwrap_or(0); 121 | let floyd = m.opt_str("floyd").and_then(|p| p.parse().ok()).unwrap_or(1.); 122 | 123 | let quality = m.opt_str("quality"); 124 | let extension = m.opt_str("ext").and_then(|s| CString::new(s).ok()); 125 | let map_file = m.opt_str("map").and_then(|s| CString::new(s).ok()); 126 | 127 | let colors = if let Some(c) = m.opt_str("colors").as_ref().or(m.free.first()).and_then(|s| s.parse().ok()) { 128 | if !m.opt_present("colors") { 129 | m.free.remove(0); 130 | if m.free.is_empty() { 131 | m.free.push("-".to_owned()); // stdin default 132 | } 133 | } 134 | c 135 | } else {0}; 136 | let using_stdin = m.free.len() == 1 && Some("-") == m.free.get(0).map(|s| s.as_str()); 137 | let mut using_stdout = using_stdin; 138 | let output_file_path = m.opt_str("o").and_then(|s| { 139 | if s == "-" { 140 | using_stdout = true; 141 | None 142 | } else { 143 | using_stdout = false; 144 | CString::new(s).ok() 145 | } 146 | }); 147 | 148 | let files: Vec<_> = m.free.drain(..).filter_map(|s| CString::new(s).ok()).collect(); 149 | let file_ptrs: Vec<_> = files.iter().map(|s| s.as_ptr()).collect(); 150 | 151 | let mut options = pngquant_options { 152 | quality: ptr::null_mut(), // handled in Rust now 153 | extension: unwrap_ptr(extension.as_ref()), 154 | output_file_path: unwrap_ptr(output_file_path.as_ref()), 155 | map_file: unwrap_ptr(map_file.as_ref()), 156 | files: file_ptrs.as_ptr(), 157 | num_files: file_ptrs.len() as c_uint, 158 | using_stdin, 159 | using_stdout, 160 | missing_arguments: !has_some_explicit_args, 161 | colors, 162 | speed: 0, // handled in Rust 163 | posterize, 164 | floyd, 165 | force: m.opt_present("force") && !m.opt_present("no-force"), 166 | skip_if_larger: m.opt_present("skip-if-larger"), 167 | strip: m.opt_present("strip"), 168 | iebug: false, 169 | last_index_transparent: false, // handled in Rust 170 | print_help: m.opt_present("h"), 171 | print_version: m.opt_present("V"), 172 | verbose: m.opt_present("v"), 173 | 174 | fixed_palette_image: ptr::null_mut(), 175 | log_callback: None, 176 | log_callback_user_info: ptr::null_mut(), 177 | fast_compression: false, 178 | min_quality_limit: false, 179 | }; 180 | 181 | if m.opt_present("nofs") || m.opt_present("ordered") { 182 | options.floyd = 0.; 183 | } 184 | 185 | if options.print_version { 186 | println!("{}", env!("CARGO_PKG_VERSION")); 187 | return SUCCESS; 188 | } 189 | 190 | if options.missing_arguments { 191 | print_full_version(&mut io::stderr(), unsafe { pngquant_c_stderr() }); 192 | print_usage(&mut io::stderr()); 193 | return MISSING_ARGUMENT; 194 | } 195 | 196 | if options.print_help { 197 | print_full_version(&mut io::stdout(), unsafe { pngquant_c_stdout() }); 198 | print_usage(&mut io::stdout()); 199 | return SUCCESS; 200 | } 201 | 202 | let mut liq = liq_attr_create().unwrap(); 203 | let liq = &mut *liq; 204 | 205 | if options.verbose { 206 | unsafe { liq_set_log_callback(liq, log_callback, Default::default()); } 207 | options.log_callback = Some(log_callback); 208 | } 209 | 210 | if m.opt_present("transbug") { 211 | liq_set_last_index_transparent(liq, i32::from(true)); 212 | } 213 | 214 | if let Some(speed) = m.opt_str("speed") { 215 | let set_ok = speed.parse().ok() 216 | .filter(|&s: &u8| (1..=11).contains(&s)) 217 | .map_or(false, |mut speed| { 218 | if speed >= 10 { 219 | options.fast_compression = true; 220 | if speed == 11 { 221 | speed = 10; 222 | options.floyd = 0.0; 223 | } 224 | } 225 | LIQ_OK == liq_set_speed(liq, speed.into()) 226 | }); 227 | if !set_ok { 228 | eprintln!("Speed should be between 1 (slow) and 11 (fast)."); 229 | return INVALID_ARGUMENT; 230 | } 231 | } 232 | 233 | if let Some(q) = quality.as_ref() { 234 | if let Some((limit, target)) = parse_quality(q) { 235 | options.min_quality_limit = limit > 0; 236 | if LIQ_OK != liq_set_quality(liq, limit.into(), target.into()) { 237 | eprintln!("Quality value(s) must be numbers in range 0-100."); 238 | return INVALID_ARGUMENT; 239 | } 240 | } else { 241 | eprintln!("Quality should be in format min-max where min and max are numbers in range 0-100."); 242 | return INVALID_ARGUMENT; 243 | } 244 | } 245 | 246 | if options.colors > 0 && LIQ_OK != liq_set_max_colors(liq, options.colors as _) { 247 | eprintln!("Number of colors must be between 2 and 256."); 248 | return INVALID_ARGUMENT; 249 | } 250 | 251 | if options.posterize > 0 && LIQ_OK != liq_set_min_posterization(liq, options.posterize as _) { 252 | eprintln!("Posterization should be number of bits in range 0-4."); 253 | return INVALID_ARGUMENT; 254 | } 255 | 256 | if !options.extension.is_null() && !options.output_file_path.is_null() { 257 | eprintln!("--ext and --output options can't be used at the same time\n"); 258 | return INVALID_ARGUMENT; 259 | } 260 | 261 | // new filename extension depends on options used. Typically basename-fs8.png 262 | if options.extension.is_null() { 263 | options.extension = if options.floyd > 0. { b"-fs8.png\0" } else { b"-or8.png\0" }.as_ptr().cast(); 264 | } 265 | 266 | if !options.output_file_path.is_null() && options.num_files != 1 { 267 | eprintln!(" error: Only one input file is allowed when --output is used. This error also happens when filenames with spaces are not in quotes."); 268 | return INVALID_ARGUMENT; 269 | } 270 | 271 | if options.using_stdout && !options.using_stdin && options.num_files != 1 { 272 | eprintln!(" error: Only one input file is allowed when using the special output path \"-\" to write to stdout. This error also happens when filenames with spaces are not in quotes."); 273 | return INVALID_ARGUMENT; 274 | } 275 | 276 | if options.num_files == 0 && !options.using_stdin { 277 | eprintln!("No input files specified."); 278 | if options.verbose { 279 | print_full_version(&mut io::stdout(), unsafe { pngquant_c_stdout() }); 280 | } 281 | print_usage(&mut io::stderr()); 282 | return MISSING_ARGUMENT; 283 | } 284 | 285 | 286 | unsafe {pngquant_main_internal(&mut options, liq)} 287 | } 288 | -------------------------------------------------------------------------------- /rust/build.rs: -------------------------------------------------------------------------------- 1 | use std::env; 2 | use std::path::Path; 3 | 4 | fn main() { 5 | let target_arch = env::var("CARGO_CFG_TARGET_ARCH").expect("CARGO_CFG_TARGET_ARCH not set"); 6 | let mut cc = cc::Build::new(); 7 | cc.warnings(false); 8 | 9 | cc.define("PNGQUANT_NO_MAIN", Some("1")); 10 | 11 | if cfg!(feature = "cocoa") { 12 | if cfg!(feature = "lcms2") { 13 | println!("cargo:warning=Don't use both lcms2 and cocoa features at the same time, see --no-default-features"); 14 | } 15 | cc.define("USE_COCOA", Some("1")); 16 | } else if cfg!(feature = "lcms2") { 17 | if let Ok(p) = env::var("DEP_LCMS2_INCLUDE") { 18 | cc.include(dunce::simplified(Path::new(&p))); 19 | } 20 | cc.define("USE_LCMS", Some("1")); 21 | } 22 | 23 | if env::var("PROFILE").map(|p| p != "debug").unwrap_or(true) { 24 | cc.define("NDEBUG", Some("1")); 25 | } else { 26 | cc.define("DEBUG", Some("1")); 27 | } 28 | 29 | if target_arch == "x86_64" || target_arch == "x86" { 30 | cc.define("USE_SSE", Some("1")); 31 | } 32 | 33 | cc.file("rwpng.c"); 34 | cc.file("pngquant.c"); 35 | 36 | if let Ok(p) = env::var("DEP_IMAGEQUANT_INCLUDE") { 37 | cc.include(dunce::simplified(Path::new(&p))); 38 | } else { 39 | cc.include("lib"); 40 | cc.include("lib/imagequant-sys"); 41 | } 42 | 43 | if let Ok(p) = env::var("DEP_PNG_INCLUDE") { 44 | for p in env::split_paths(&p) { 45 | cc.include(dunce::simplified(&p)); 46 | } 47 | } 48 | 49 | cc.compile("libpngquant.a"); 50 | } 51 | -------------------------------------------------------------------------------- /rust/ffi.rs: -------------------------------------------------------------------------------- 1 | #![allow(non_camel_case_types)] 2 | 3 | use libc::FILE; 4 | use imagequant_sys::*; 5 | use std::os::raw::{c_char, c_uint, c_void}; 6 | 7 | extern "C" { 8 | pub static PNGQUANT_USAGE: *const c_char; 9 | pub fn pngquant_internal_print_config(fd: *mut libc::FILE); 10 | 11 | #[allow(improper_ctypes)] 12 | pub fn pngquant_main_internal(options: &mut pngquant_options, liq: *mut liq_attr) -> pngquant_error; 13 | pub fn pngquant_c_stderr() -> *mut FILE; 14 | pub fn pngquant_c_stdout() -> *mut FILE; 15 | } 16 | 17 | #[repr(C)] 18 | #[derive(Debug, Copy, Clone)] 19 | #[allow(dead_code)] 20 | #[allow(non_camel_case_types)] 21 | #[allow(clippy::upper_case_acronyms)] 22 | #[non_exhaustive] 23 | pub enum pngquant_error { 24 | SUCCESS = 0, 25 | MISSING_ARGUMENT = 1, 26 | READ_ERROR = 2, 27 | INVALID_ARGUMENT = 4, 28 | NOT_OVERWRITING_ERROR = 15, 29 | CANT_WRITE_ERROR = 16, 30 | OUT_OF_MEMORY_ERROR = 17, 31 | WRONG_ARCHITECTURE = 18, // Missing SSE 32 | PNG_OUT_OF_MEMORY_ERROR = 24, 33 | LIBPNG_FATAL_ERROR = 25, 34 | WRONG_INPUT_COLOR_TYPE = 26, 35 | LIBPNG_INIT_ERROR = 35, 36 | LCMS_FATAL_ERROR = 45, 37 | TOO_LARGE_FILE = 98, 38 | TOO_LOW_QUALITY = 99, 39 | } 40 | 41 | #[repr(C)] 42 | pub struct pngquant_options { 43 | pub fixed_palette_image: *mut liq_image<'static>, 44 | pub log_callback: Option, 45 | pub log_callback_user_info: *mut c_void, 46 | pub quality: *const c_char, 47 | pub extension: *const c_char, 48 | pub output_file_path: *const c_char, 49 | pub map_file: *const c_char, 50 | pub files: *const *const c_char, 51 | pub num_files: c_uint, 52 | pub colors: c_uint, 53 | pub speed: c_uint, 54 | pub posterize: c_uint, 55 | pub floyd: f32, 56 | pub using_stdin: bool, 57 | pub using_stdout: bool, 58 | pub force: bool, 59 | pub fast_compression: bool, 60 | pub min_quality_limit: bool, 61 | pub skip_if_larger: bool, 62 | pub strip: bool, 63 | pub iebug: bool, 64 | pub last_index_transparent: bool, 65 | pub print_help: bool, 66 | pub print_version: bool, 67 | pub missing_arguments: bool, 68 | pub verbose: bool, 69 | } 70 | -------------------------------------------------------------------------------- /rust/rwpng_cocoa.rs: -------------------------------------------------------------------------------- 1 | use libc::{FILE, fileno, malloc}; 2 | use std::fs::File; 3 | use std::io::prelude::*; 4 | use std::os::unix::io::FromRawFd; 5 | use crate::ffi::pngquant_error; 6 | 7 | #[no_mangle] 8 | pub extern "C" fn rwpng_read_image32_cocoa(file_handle: *mut FILE, width: &mut u32, height: &mut u32, file_size: &mut usize, out: &mut *mut cocoa_image::RGBA8) -> pngquant_error { 9 | let mut file = unsafe { 10 | File::from_raw_fd(fileno(file_handle)) 11 | }; 12 | 13 | let mut data = Vec::new(); 14 | match file.read_to_end(&mut data) { 15 | Ok(_) => {}, 16 | Err(_) => return pngquant_error::READ_ERROR, 17 | }; 18 | 19 | let image = match cocoa_image::decode_image_as_rgba(&data) { 20 | Ok(img) => img, 21 | Err(_) => return pngquant_error::LIBPNG_FATAL_ERROR, 22 | }; 23 | 24 | let (buf, w, h) = image.into_contiguous_buf(); 25 | *file_size = data.len(); 26 | *width = w as u32; 27 | *height = h as u32; 28 | unsafe { 29 | *out = malloc(buf.len() * std::mem::size_of::()) as *mut cocoa_image::RGBA8; 30 | if (*out).is_null() { 31 | return pngquant_error::OUT_OF_MEMORY_ERROR; 32 | } 33 | std::slice::from_raw_parts_mut(*out, buf.len()).copy_from_slice(&buf); 34 | } 35 | 36 | pngquant_error::SUCCESS 37 | } 38 | -------------------------------------------------------------------------------- /rwpng.c: -------------------------------------------------------------------------------- 1 | /* 2 | ** PNG read/write functions 3 | ** 4 | ** © 1998-2000 by Greg Roelofs. 5 | ** © 2009-2017 by Kornel Lesiński. 6 | ** 7 | ** See COPYRIGHT file for license. 8 | */ 9 | 10 | #include 11 | #include 12 | #include 13 | #include 14 | 15 | #include "png.h" /* if this include fails, you need to install libpng (e.g. libpng-devel package) */ 16 | #include "rwpng.h" 17 | #if USE_LCMS 18 | #include "lcms2.h" 19 | #endif 20 | 21 | #ifndef Z_BEST_COMPRESSION 22 | #define Z_BEST_COMPRESSION 9 23 | #endif 24 | #ifndef Z_BEST_SPEED 25 | #define Z_BEST_SPEED 1 26 | #endif 27 | 28 | #ifdef _OPENMP 29 | #include 30 | #else 31 | #define omp_get_max_threads() 1 32 | #endif 33 | 34 | #if PNG_LIBPNG_VER < 10400 35 | #error libpng version 1.4 or later is required. 1.6 is recommended. You have an obsolete version of libpng or compiling on an outdated/unsupported operating system. Please upgrade. 36 | #endif 37 | 38 | #if PNG_LIBPNG_VER < 10500 39 | typedef png_const_charp png_const_bytep; 40 | #endif 41 | 42 | static void rwpng_error_handler(png_structp png_ptr, png_const_charp msg); 43 | pngquant_error rwpng_read_image32_cocoa(FILE *infile, uint32_t *width, uint32_t *height, size_t *file_size, rwpng_rgba **image_data); 44 | 45 | 46 | void rwpng_version_info(FILE *fp) 47 | { 48 | const char *pngver = png_get_header_ver(NULL); 49 | 50 | #if USE_COCOA 51 | fprintf(fp, " Color profiles are supported via Cocoa. Using libpng %s.\n", pngver); 52 | #elif USE_LCMS 53 | fprintf(fp, " Color profiles are supported via Little CMS. Using libpng %s.\n", pngver); 54 | #else 55 | fprintf(fp, " Compiled with no support for color profiles. Using libpng %s.\n", pngver); 56 | #endif 57 | 58 | #if PNG_LIBPNG_VER < 10600 59 | if (strcmp(pngver, "1.3.") < 0) { 60 | fputs("\nWARNING: Your version of libpng is outdated and may produce corrupted files.\n" 61 | "Please recompile pngquant with the current version of libpng (1.6 or later).\n", fp); 62 | } else if (strcmp(pngver, "1.6.") < 0) { 63 | #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED) 64 | fputs("\nWARNING: Your version of libpng is old and has buggy support for custom chunks.\n" 65 | "Please recompile pngquant with the current version of libpng (1.6 or later).\n", fp); 66 | #endif 67 | } 68 | #endif 69 | } 70 | 71 | 72 | struct rwpng_read_data { 73 | FILE *const fp; 74 | png_size_t bytes_read; 75 | }; 76 | 77 | #if !USE_COCOA 78 | static void user_read_data(png_structp png_ptr, png_bytep data, png_size_t length) 79 | { 80 | struct rwpng_read_data *read_data = (struct rwpng_read_data *)png_get_io_ptr(png_ptr); 81 | 82 | png_size_t read = fread(data, 1, length, read_data->fp); 83 | if (!read) { 84 | png_error(png_ptr, "Read error"); 85 | } 86 | read_data->bytes_read += read; 87 | } 88 | #endif 89 | 90 | struct rwpng_write_state { 91 | FILE *outfile; 92 | png_size_t maximum_file_size; 93 | png_size_t bytes_written; 94 | pngquant_error retval; 95 | }; 96 | 97 | static void user_write_data(png_structp png_ptr, png_bytep data, png_size_t length) 98 | { 99 | struct rwpng_write_state *write_state = (struct rwpng_write_state *)png_get_io_ptr(png_ptr); 100 | 101 | if (SUCCESS != write_state->retval) { 102 | return; 103 | } 104 | 105 | if (!fwrite(data, length, 1, write_state->outfile)) { 106 | write_state->retval = CANT_WRITE_ERROR; 107 | } 108 | 109 | write_state->bytes_written += length; 110 | } 111 | 112 | static void user_flush_data(png_structp png_ptr) 113 | { 114 | // libpng never calls this :( 115 | } 116 | 117 | 118 | static png_bytepp rwpng_create_row_pointers(png_infop info_ptr, png_structp png_ptr, unsigned char *base, size_t height, png_size_t rowbytes) 119 | { 120 | if (!rowbytes) { 121 | rowbytes = png_get_rowbytes(png_ptr, info_ptr); 122 | } 123 | 124 | png_bytepp row_pointers = malloc(height * sizeof(row_pointers[0])); 125 | if (!row_pointers) return NULL; 126 | for(size_t row = 0; row < height; row++) { 127 | row_pointers[row] = base + row * rowbytes; 128 | } 129 | return row_pointers; 130 | } 131 | 132 | #if !USE_COCOA 133 | static int read_chunk_callback(png_structp png_ptr, png_unknown_chunkp in_chunk) 134 | { 135 | if (0 == memcmp("iCCP", in_chunk->name, 5) || 136 | 0 == memcmp("cHRM", in_chunk->name, 5) || 137 | 0 == memcmp("gAMA", in_chunk->name, 5)) { 138 | return 0; // not handled 139 | } 140 | 141 | if (in_chunk->location == 0 ) { 142 | return 1; // ignore chunks with invalid location 143 | } 144 | 145 | struct rwpng_chunk **head = (struct rwpng_chunk **)png_get_user_chunk_ptr(png_ptr); 146 | 147 | struct rwpng_chunk *chunk = malloc(sizeof(struct rwpng_chunk)); 148 | memcpy(chunk->name, in_chunk->name, 5); 149 | chunk->size = in_chunk->size; 150 | chunk->location = in_chunk->location; 151 | chunk->data = in_chunk->size ? malloc(in_chunk->size) : NULL; 152 | if (in_chunk->size) { 153 | memcpy(chunk->data, in_chunk->data, in_chunk->size); 154 | } 155 | 156 | chunk->next = *head; 157 | *head = chunk; 158 | 159 | return 1; // marks as "handled", libpng won't store it 160 | } 161 | #endif 162 | 163 | /* 164 | retval: 165 | 0 = success 166 | 21 = bad sig 167 | 22 = bad IHDR 168 | 24 = insufficient memory 169 | 25 = libpng error (via longjmp()) 170 | 26 = wrong PNG color type (no alpha channel) 171 | */ 172 | 173 | #if !USE_COCOA 174 | static void rwpng_warning_stderr_handler(png_structp png_ptr, png_const_charp msg) { 175 | fprintf(stderr, " libpng warning: %s\n", msg); 176 | } 177 | 178 | static void rwpng_warning_silent_handler(png_structp png_ptr, png_const_charp msg) { 179 | } 180 | 181 | static pngquant_error rwpng_read_image24_libpng(FILE *infile, png24_image *mainprog_ptr, int strip, int verbose) 182 | { 183 | png_structp png_ptr = NULL; 184 | png_infop info_ptr = NULL; 185 | png_size_t rowbytes; 186 | int color_type, bit_depth; 187 | 188 | png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, mainprog_ptr, 189 | rwpng_error_handler, verbose ? rwpng_warning_stderr_handler : rwpng_warning_silent_handler); 190 | if (!png_ptr) { 191 | return PNG_OUT_OF_MEMORY_ERROR; /* out of memory */ 192 | } 193 | 194 | info_ptr = png_create_info_struct(png_ptr); 195 | if (!info_ptr) { 196 | png_destroy_read_struct(&png_ptr, NULL, NULL); 197 | return PNG_OUT_OF_MEMORY_ERROR; /* out of memory */ 198 | } 199 | 200 | /* setjmp() must be called in every function that calls a non-trivial 201 | * libpng function */ 202 | 203 | if (setjmp(mainprog_ptr->jmpbuf)) { 204 | png_destroy_read_struct(&png_ptr, &info_ptr, NULL); 205 | return LIBPNG_FATAL_ERROR; /* fatal libpng error (via longjmp()) */ 206 | } 207 | 208 | #if defined(PNG_SKIP_sRGB_CHECK_PROFILE) && defined(PNG_SET_OPTION_SUPPORTED) 209 | png_set_option(png_ptr, PNG_SKIP_sRGB_CHECK_PROFILE, PNG_OPTION_ON); 210 | #endif 211 | 212 | #if PNG_LIBPNG_VER >= 10500 && defined(PNG_UNKNOWN_CHUNKS_SUPPORTED) 213 | if (!strip) { 214 | /* copy standard chunks too */ 215 | png_set_keep_unknown_chunks(png_ptr, PNG_HANDLE_CHUNK_IF_SAFE, (png_const_bytep)"pHYs\0iTXt\0tEXt\0zTXt", 4); 216 | } 217 | #endif 218 | if (!strip) { 219 | png_set_read_user_chunk_fn(png_ptr, &mainprog_ptr->chunks, read_chunk_callback); 220 | } 221 | 222 | struct rwpng_read_data read_data = {infile, 0}; 223 | png_set_read_fn(png_ptr, &read_data, user_read_data); 224 | 225 | png_read_info(png_ptr, info_ptr); /* read all PNG info up to image data */ 226 | 227 | /* alternatively, could make separate calls to png_get_image_width(), 228 | * etc., but want bit_depth and color_type for later [don't care about 229 | * compression_type and filter_type => NULLs] */ 230 | 231 | png_get_IHDR(png_ptr, info_ptr, &mainprog_ptr->width, &mainprog_ptr->height, 232 | &bit_depth, &color_type, NULL, NULL, NULL); 233 | 234 | /* expand palette images to RGB, low-bit-depth grayscale images to 8 bits, 235 | * transparency chunks to full alpha channel; strip 16-bit-per-sample 236 | * images to 8 bits per sample; and convert grayscale to RGB[A] */ 237 | 238 | /* GRR TO DO: preserve all safe-to-copy ancillary PNG chunks */ 239 | 240 | if (!(color_type & PNG_COLOR_MASK_ALPHA)) { 241 | #ifdef PNG_READ_FILLER_SUPPORTED 242 | png_set_expand(png_ptr); 243 | png_set_filler(png_ptr, 65535L, PNG_FILLER_AFTER); 244 | #else 245 | fprintf(stderr, "pngquant readpng: image is neither RGBA nor GA\n"); 246 | png_destroy_read_struct(&png_ptr, &info_ptr, NULL); 247 | mainprog_ptr->retval = WRONG_INPUT_COLOR_TYPE; 248 | return mainprog_ptr->retval; 249 | #endif 250 | } 251 | 252 | if (bit_depth == 16) { 253 | png_set_strip_16(png_ptr); 254 | } 255 | 256 | if (!(color_type & PNG_COLOR_MASK_COLOR)) { 257 | png_set_gray_to_rgb(png_ptr); 258 | } 259 | 260 | /* get source gamma for gamma correction, or use sRGB default */ 261 | double gamma = 0.45455; 262 | if (png_get_valid(png_ptr, info_ptr, PNG_INFO_sRGB)) { 263 | mainprog_ptr->input_color = RWPNG_SRGB; 264 | mainprog_ptr->output_color = RWPNG_SRGB; 265 | } else { 266 | png_get_gAMA(png_ptr, info_ptr, &gamma); 267 | if (gamma > 0 && gamma <= 1.0) { 268 | mainprog_ptr->input_color = RWPNG_GAMA_ONLY; 269 | mainprog_ptr->output_color = RWPNG_GAMA_ONLY; 270 | } else { 271 | fprintf(stderr, "pngquant readpng: ignored out-of-range gamma %f\n", gamma); 272 | mainprog_ptr->input_color = RWPNG_NONE; 273 | mainprog_ptr->output_color = RWPNG_NONE; 274 | gamma = 0.45455; 275 | } 276 | } 277 | mainprog_ptr->gamma = gamma; 278 | 279 | png_set_interlace_handling(png_ptr); 280 | 281 | /* all transformations have been registered; now update info_ptr data, 282 | * get rowbytes and channels, and allocate image memory */ 283 | 284 | png_read_update_info(png_ptr, info_ptr); 285 | 286 | rowbytes = png_get_rowbytes(png_ptr, info_ptr); 287 | 288 | // For overflow safety reject images that won't fit in 32-bit 289 | if (rowbytes > INT_MAX/mainprog_ptr->height) { 290 | png_destroy_read_struct(&png_ptr, &info_ptr, NULL); 291 | return PNG_OUT_OF_MEMORY_ERROR; 292 | } 293 | 294 | if ((mainprog_ptr->rgba_data = malloc(rowbytes * mainprog_ptr->height)) == NULL) { 295 | fprintf(stderr, "pngquant readpng: unable to allocate image data\n"); 296 | png_destroy_read_struct(&png_ptr, &info_ptr, NULL); 297 | return PNG_OUT_OF_MEMORY_ERROR; 298 | } 299 | 300 | png_bytepp row_pointers = rwpng_create_row_pointers(info_ptr, png_ptr, mainprog_ptr->rgba_data, mainprog_ptr->height, 0); 301 | 302 | /* now we can go ahead and just read the whole image */ 303 | 304 | png_read_image(png_ptr, row_pointers); 305 | 306 | /* and we're done! (png_read_end() can be omitted if no processing of 307 | * post-IDAT text/time/etc. is desired) */ 308 | 309 | png_read_end(png_ptr, NULL); 310 | 311 | #if USE_LCMS 312 | #if PNG_LIBPNG_VER < 10500 313 | png_charp ProfileData; 314 | #else 315 | png_bytep ProfileData; 316 | #endif 317 | png_uint_32 ProfileLen; 318 | 319 | cmsHPROFILE hInProfile = NULL; 320 | 321 | /* color_type is read from the image before conversion to RGBA */ 322 | int COLOR_PNG = color_type & PNG_COLOR_MASK_COLOR; 323 | 324 | /* embedded ICC profile */ 325 | if (png_get_iCCP(png_ptr, info_ptr, &(png_charp){0}, &(int){0}, &ProfileData, &ProfileLen)) { 326 | 327 | hInProfile = cmsOpenProfileFromMem(ProfileData, ProfileLen); 328 | cmsColorSpaceSignature colorspace = cmsGetColorSpace(hInProfile); 329 | 330 | /* only RGB (and GRAY) valid for PNGs */ 331 | if (colorspace == cmsSigRgbData && COLOR_PNG) { 332 | mainprog_ptr->input_color = RWPNG_ICCP; 333 | mainprog_ptr->output_color = RWPNG_SRGB; 334 | } else { 335 | if (colorspace == cmsSigGrayData && !COLOR_PNG) { 336 | mainprog_ptr->input_color = RWPNG_ICCP_WARN_GRAY; 337 | mainprog_ptr->output_color = RWPNG_SRGB; 338 | } 339 | cmsCloseProfile(hInProfile); 340 | hInProfile = NULL; 341 | } 342 | } 343 | 344 | /* build RGB profile from cHRM and gAMA */ 345 | if (hInProfile == NULL && COLOR_PNG && 346 | !png_get_valid(png_ptr, info_ptr, PNG_INFO_sRGB) && 347 | png_get_valid(png_ptr, info_ptr, PNG_INFO_gAMA) && 348 | png_get_valid(png_ptr, info_ptr, PNG_INFO_cHRM)) { 349 | 350 | cmsCIExyY WhitePoint; 351 | cmsCIExyYTRIPLE Primaries; 352 | 353 | png_get_cHRM(png_ptr, info_ptr, &WhitePoint.x, &WhitePoint.y, 354 | &Primaries.Red.x, &Primaries.Red.y, 355 | &Primaries.Green.x, &Primaries.Green.y, 356 | &Primaries.Blue.x, &Primaries.Blue.y); 357 | 358 | WhitePoint.Y = Primaries.Red.Y = Primaries.Green.Y = Primaries.Blue.Y = 1.0; 359 | 360 | cmsToneCurve *GammaTable[3]; 361 | GammaTable[0] = GammaTable[1] = GammaTable[2] = cmsBuildGamma(NULL, 1/gamma); 362 | 363 | hInProfile = cmsCreateRGBProfile(&WhitePoint, &Primaries, GammaTable); 364 | 365 | cmsFreeToneCurve(GammaTable[0]); 366 | 367 | mainprog_ptr->input_color = RWPNG_GAMA_CHRM; 368 | mainprog_ptr->output_color = RWPNG_SRGB; 369 | } 370 | 371 | /* transform image to sRGB colorspace */ 372 | if (hInProfile != NULL) { 373 | 374 | cmsHPROFILE hOutProfile = cmsCreate_sRGBProfile(); 375 | cmsHTRANSFORM hTransform = cmsCreateTransform(hInProfile, TYPE_RGBA_8, 376 | hOutProfile, TYPE_RGBA_8, 377 | INTENT_PERCEPTUAL, 378 | omp_get_max_threads() > 1 ? cmsFLAGS_NOCACHE : 0); 379 | if(!hTransform) { 380 | png_destroy_read_struct(&png_ptr, &info_ptr, NULL); 381 | cmsCloseProfile(hOutProfile); 382 | cmsCloseProfile(hInProfile); 383 | return LCMS_FATAL_ERROR; 384 | } 385 | 386 | #pragma omp parallel for \ 387 | if (mainprog_ptr->height*mainprog_ptr->width > 8000) \ 388 | schedule(static) 389 | for (unsigned int i = 0; i < mainprog_ptr->height; i++) { 390 | /* It is safe to use the same block for input and output, 391 | when both are of the same TYPE. */ 392 | cmsDoTransform(hTransform, row_pointers[i], 393 | row_pointers[i], 394 | mainprog_ptr->width); 395 | } 396 | 397 | cmsDeleteTransform(hTransform); 398 | cmsCloseProfile(hOutProfile); 399 | cmsCloseProfile(hInProfile); 400 | 401 | mainprog_ptr->gamma = 0.45455; 402 | } 403 | #endif 404 | 405 | png_destroy_read_struct(&png_ptr, &info_ptr, NULL); 406 | 407 | mainprog_ptr->file_size = read_data.bytes_read; 408 | mainprog_ptr->row_pointers = (unsigned char **)row_pointers; 409 | 410 | return SUCCESS; 411 | } 412 | #endif 413 | 414 | static void rwpng_free_chunks(struct rwpng_chunk *chunk) { 415 | if (!chunk) return; 416 | rwpng_free_chunks(chunk->next); 417 | free(chunk->data); 418 | free(chunk); 419 | } 420 | 421 | void rwpng_free_image24(png24_image *image) 422 | { 423 | free(image->row_pointers); 424 | image->row_pointers = NULL; 425 | 426 | free(image->rgba_data); 427 | image->rgba_data = NULL; 428 | 429 | rwpng_free_chunks(image->chunks); 430 | image->chunks = NULL; 431 | } 432 | 433 | void rwpng_free_image8(png8_image *image) 434 | { 435 | free(image->indexed_data); 436 | image->indexed_data = NULL; 437 | 438 | free(image->row_pointers); 439 | image->row_pointers = NULL; 440 | 441 | rwpng_free_chunks(image->chunks); 442 | image->chunks = NULL; 443 | } 444 | 445 | pngquant_error rwpng_read_image24(FILE *infile, png24_image *out, int strip, int verbose) 446 | { 447 | #if USE_COCOA 448 | rwpng_rgba *pixel_data; 449 | pngquant_error res = rwpng_read_image32_cocoa(infile, &out->width, &out->height, &out->file_size, &pixel_data); 450 | if (res != SUCCESS) { 451 | return res; 452 | } 453 | out->gamma = 0.45455; 454 | out->input_color = RWPNG_COCOA; 455 | out->output_color = RWPNG_SRGB; 456 | out->rgba_data = (unsigned char *)pixel_data; 457 | out->row_pointers = malloc(sizeof(out->row_pointers[0])*out->height); 458 | for(int i=0; i < out->height; i++) { 459 | out->row_pointers[i] = (unsigned char *)&pixel_data[out->width*i]; 460 | } 461 | return SUCCESS; 462 | #else 463 | return rwpng_read_image24_libpng(infile, out, strip, verbose); 464 | #endif 465 | } 466 | 467 | 468 | static pngquant_error rwpng_write_image_init(rwpng_png_image *mainprog_ptr, png_structpp png_ptr_p, png_infopp info_ptr_p, int fast_compression) 469 | { 470 | /* could also replace libpng warning-handler (final NULL), but no need: */ 471 | 472 | *png_ptr_p = png_create_write_struct(PNG_LIBPNG_VER_STRING, mainprog_ptr, rwpng_error_handler, NULL); 473 | 474 | if (!(*png_ptr_p)) { 475 | return LIBPNG_INIT_ERROR; /* out of memory */ 476 | } 477 | 478 | *info_ptr_p = png_create_info_struct(*png_ptr_p); 479 | if (!(*info_ptr_p)) { 480 | png_destroy_write_struct(png_ptr_p, NULL); 481 | return LIBPNG_INIT_ERROR; /* out of memory */ 482 | } 483 | 484 | /* setjmp() must be called in every function that calls a PNG-writing 485 | * libpng function, unless an alternate error handler was installed-- 486 | * but compatible error handlers must either use longjmp() themselves 487 | * (as in this program) or exit immediately, so here we go: */ 488 | 489 | if (setjmp(mainprog_ptr->jmpbuf)) { 490 | png_destroy_write_struct(png_ptr_p, info_ptr_p); 491 | return LIBPNG_INIT_ERROR; /* libpng error (via longjmp()) */ 492 | } 493 | 494 | png_set_compression_level(*png_ptr_p, fast_compression ? Z_BEST_SPEED : Z_BEST_COMPRESSION); 495 | png_set_compression_mem_level(*png_ptr_p, fast_compression ? 9 : 5); // judging by optipng results, smaller mem makes libpng compress slightly better 496 | 497 | return SUCCESS; 498 | } 499 | 500 | 501 | static void rwpng_write_end(png_infopp info_ptr_p, png_structpp png_ptr_p, png_bytepp row_pointers) 502 | { 503 | png_write_info(*png_ptr_p, *info_ptr_p); 504 | 505 | png_set_packing(*png_ptr_p); 506 | 507 | png_write_image(*png_ptr_p, row_pointers); 508 | 509 | png_write_end(*png_ptr_p, NULL); 510 | 511 | png_destroy_write_struct(png_ptr_p, info_ptr_p); 512 | } 513 | 514 | static void rwpng_set_gamma(png_infop info_ptr, png_structp png_ptr, double gamma, rwpng_color_transform color) 515 | { 516 | if (color != RWPNG_GAMA_ONLY && color != RWPNG_NONE) { 517 | png_set_gAMA(png_ptr, info_ptr, gamma); 518 | } 519 | if (color == RWPNG_SRGB) { 520 | png_set_sRGB(png_ptr, info_ptr, 0); // 0 = Perceptual 521 | } 522 | } 523 | 524 | pngquant_error rwpng_write_image8(FILE *outfile, png8_image *mainprog_ptr) 525 | { 526 | png_structp png_ptr; 527 | png_infop info_ptr; 528 | 529 | if (mainprog_ptr->num_palette > 256) return INVALID_ARGUMENT; 530 | 531 | pngquant_error retval = rwpng_write_image_init((rwpng_png_image*)mainprog_ptr, &png_ptr, &info_ptr, mainprog_ptr->fast_compression); 532 | if (retval) return retval; 533 | 534 | struct rwpng_write_state write_state; 535 | write_state = (struct rwpng_write_state){ 536 | .outfile = outfile, 537 | .maximum_file_size = mainprog_ptr->maximum_file_size, 538 | .retval = SUCCESS, 539 | }; 540 | png_set_write_fn(png_ptr, &write_state, user_write_data, user_flush_data); 541 | 542 | // Palette images generally don't gain anything from filtering 543 | png_set_filter(png_ptr, PNG_FILTER_TYPE_BASE, PNG_FILTER_VALUE_NONE); 544 | 545 | rwpng_set_gamma(info_ptr, png_ptr, mainprog_ptr->gamma, mainprog_ptr->output_color); 546 | 547 | /* set the image parameters appropriately */ 548 | int sample_depth; 549 | #if PNG_LIBPNG_VER > 10400 /* old libpng corrupts files with low depth */ 550 | if (mainprog_ptr->num_palette <= 2) 551 | sample_depth = 1; 552 | else if (mainprog_ptr->num_palette <= 4) 553 | sample_depth = 2; 554 | else if (mainprog_ptr->num_palette <= 16) 555 | sample_depth = 4; 556 | else 557 | #endif 558 | sample_depth = 8; 559 | 560 | struct rwpng_chunk *chunk = mainprog_ptr->chunks; 561 | mainprog_ptr->metadata_size = 0; 562 | int chunk_num=0; 563 | while(chunk) { 564 | png_unknown_chunk pngchunk = { 565 | .size = chunk->size, 566 | .data = chunk->data, 567 | .location = chunk->location, 568 | }; 569 | memcpy(pngchunk.name, chunk->name, 5); 570 | png_set_unknown_chunks(png_ptr, info_ptr, &pngchunk, 1); 571 | 572 | #if defined(PNG_HAVE_IHDR) && PNG_LIBPNG_VER < 10600 573 | png_set_unknown_chunk_location(png_ptr, info_ptr, chunk_num, pngchunk.location ? pngchunk.location : PNG_HAVE_IHDR); 574 | #endif 575 | 576 | mainprog_ptr->metadata_size += chunk->size + 12; 577 | chunk = chunk->next; 578 | chunk_num++; 579 | } 580 | 581 | png_set_IHDR(png_ptr, info_ptr, mainprog_ptr->width, mainprog_ptr->height, 582 | sample_depth, PNG_COLOR_TYPE_PALETTE, 583 | 0, PNG_COMPRESSION_TYPE_DEFAULT, 584 | PNG_FILTER_TYPE_BASE); 585 | 586 | png_color palette[256]; 587 | png_byte trans[256]; 588 | unsigned int num_trans = 0; 589 | for(unsigned int i = 0; i < mainprog_ptr->num_palette; i++) { 590 | palette[i] = (png_color){ 591 | .red = mainprog_ptr->palette[i].r, 592 | .green = mainprog_ptr->palette[i].g, 593 | .blue = mainprog_ptr->palette[i].b, 594 | }; 595 | trans[i] = mainprog_ptr->palette[i].a; 596 | if (mainprog_ptr->palette[i].a < 255) { 597 | num_trans = i+1; 598 | } 599 | } 600 | 601 | png_set_PLTE(png_ptr, info_ptr, palette, mainprog_ptr->num_palette); 602 | 603 | if (num_trans > 0) { 604 | png_set_tRNS(png_ptr, info_ptr, trans, num_trans, NULL); 605 | } 606 | 607 | rwpng_write_end(&info_ptr, &png_ptr, mainprog_ptr->row_pointers); 608 | 609 | if (SUCCESS == write_state.retval && write_state.maximum_file_size && write_state.bytes_written > write_state.maximum_file_size) { 610 | return TOO_LARGE_FILE; 611 | } 612 | 613 | return write_state.retval; 614 | } 615 | 616 | pngquant_error rwpng_write_image24(FILE *outfile, const png24_image *mainprog_ptr) 617 | { 618 | png_structp png_ptr; 619 | png_infop info_ptr; 620 | 621 | pngquant_error retval = rwpng_write_image_init((rwpng_png_image*)mainprog_ptr, &png_ptr, &info_ptr, 0); 622 | if (retval) return retval; 623 | 624 | png_init_io(png_ptr, outfile); 625 | 626 | rwpng_set_gamma(info_ptr, png_ptr, mainprog_ptr->gamma, mainprog_ptr->output_color); 627 | 628 | png_set_IHDR(png_ptr, info_ptr, mainprog_ptr->width, mainprog_ptr->height, 629 | 8, PNG_COLOR_TYPE_RGB_ALPHA, 630 | 0, PNG_COMPRESSION_TYPE_DEFAULT, 631 | PNG_FILTER_TYPE_BASE); 632 | 633 | 634 | png_bytepp row_pointers = rwpng_create_row_pointers(info_ptr, png_ptr, mainprog_ptr->rgba_data, mainprog_ptr->height, 0); 635 | 636 | rwpng_write_end(&info_ptr, &png_ptr, row_pointers); 637 | 638 | free(row_pointers); 639 | 640 | return SUCCESS; 641 | } 642 | 643 | static void rwpng_error_handler(png_structp png_ptr, png_const_charp msg) 644 | { 645 | rwpng_png_image *mainprog_ptr; 646 | 647 | /* This function, aside from the extra step of retrieving the "error 648 | * pointer" (below) and the fact that it exists within the application 649 | * rather than within libpng, is essentially identical to libpng's 650 | * default error handler. The second point is critical: since both 651 | * setjmp() and longjmp() are called from the same code, they are 652 | * guaranteed to have compatible notions of how big a jmp_buf is, 653 | * regardless of whether _BSD_SOURCE or anything else has (or has not) 654 | * been defined. */ 655 | 656 | fprintf(stderr, " error: %s (libpng failed)\n", msg); 657 | fflush(stderr); 658 | 659 | mainprog_ptr = png_get_error_ptr(png_ptr); 660 | if (mainprog_ptr == NULL) abort(); 661 | 662 | longjmp(mainprog_ptr->jmpbuf, 1); 663 | } 664 | -------------------------------------------------------------------------------- /rwpng.h: -------------------------------------------------------------------------------- 1 | /* 2 | ** PNG read/write functions 3 | ** 4 | ** © 1998-2000 by Greg Roelofs. 5 | ** © 2009-2017 by Kornel Lesiński. 6 | ** 7 | ** See COPYRIGHT file for license. 8 | */ 9 | 10 | #ifndef RWPNG_H 11 | #define RWPNG_H 12 | 13 | #include 14 | #include 15 | #include 16 | #include 17 | 18 | #ifndef USE_COCOA 19 | #define USE_COCOA 0 20 | #endif 21 | 22 | typedef enum { 23 | SUCCESS = 0, 24 | MISSING_ARGUMENT = 1, 25 | READ_ERROR = 2, 26 | INVALID_ARGUMENT = 4, 27 | NOT_OVERWRITING_ERROR = 15, 28 | CANT_WRITE_ERROR = 16, 29 | OUT_OF_MEMORY_ERROR = 17, 30 | WRONG_ARCHITECTURE = 18, // Missing SSE 31 | PNG_OUT_OF_MEMORY_ERROR = 24, 32 | LIBPNG_FATAL_ERROR = 25, 33 | WRONG_INPUT_COLOR_TYPE = 26, 34 | LIBPNG_INIT_ERROR = 35, 35 | LCMS_FATAL_ERROR = 45, 36 | TOO_LARGE_FILE = 98, 37 | TOO_LOW_QUALITY = 99, 38 | } pngquant_error; 39 | 40 | typedef struct rwpng_rgba { 41 | unsigned char r,g,b,a; 42 | } rwpng_rgba; 43 | 44 | struct rwpng_chunk { 45 | struct rwpng_chunk *next; 46 | unsigned char *data; 47 | size_t size; 48 | unsigned char name[5]; 49 | unsigned char location; 50 | }; 51 | 52 | typedef enum { 53 | RWPNG_NONE, 54 | RWPNG_SRGB, // sRGB chunk 55 | RWPNG_ICCP, // used ICC profile 56 | RWPNG_ICCP_WARN_GRAY, // ignore and warn about GRAY ICC profile 57 | RWPNG_GAMA_CHRM, // used gAMA and cHRM 58 | RWPNG_GAMA_ONLY, // used gAMA only (i.e. not sRGB) 59 | RWPNG_COCOA, // Colors handled by Cocoa reader 60 | } rwpng_color_transform; 61 | 62 | typedef struct { 63 | jmp_buf jmpbuf; 64 | uint32_t width; 65 | uint32_t height; 66 | size_t file_size; 67 | double gamma; 68 | unsigned char **row_pointers; 69 | unsigned char *rgba_data; 70 | struct rwpng_chunk *chunks; 71 | rwpng_color_transform input_color; 72 | rwpng_color_transform output_color; 73 | } png24_image; 74 | 75 | typedef struct { 76 | jmp_buf jmpbuf; 77 | uint32_t width; 78 | uint32_t height; 79 | size_t maximum_file_size; 80 | size_t metadata_size; 81 | double gamma; 82 | unsigned char **row_pointers; 83 | unsigned char *indexed_data; 84 | struct rwpng_chunk *chunks; 85 | unsigned int num_palette; 86 | rwpng_rgba palette[256]; 87 | rwpng_color_transform output_color; 88 | char fast_compression; 89 | } png8_image; 90 | 91 | typedef union { 92 | jmp_buf jmpbuf; 93 | png24_image png24; 94 | png8_image png8; 95 | } rwpng_png_image; 96 | 97 | /* prototypes for public functions in rwpng.c */ 98 | 99 | void rwpng_version_info(FILE *fp); 100 | 101 | pngquant_error rwpng_read_image24(FILE *infile, png24_image *mainprog_ptr, int strip, int verbose); 102 | pngquant_error rwpng_write_image8(FILE *outfile, png8_image *mainprog_ptr); 103 | pngquant_error rwpng_write_image24(FILE *outfile, const png24_image *mainprog_ptr); 104 | void rwpng_free_image24(png24_image *); 105 | void rwpng_free_image8(png8_image *); 106 | 107 | #endif 108 | -------------------------------------------------------------------------------- /snapcraft.yaml: -------------------------------------------------------------------------------- 1 | name: pngquant 2 | version: 3.0.3 3 | summary: pngquant 4 | description: | 5 | Lossy PNG compressor — pngquant command based 6 | on libimagequant library https://pngquant.org 7 | 8 | base: core20 9 | confinement: strict 10 | 11 | apps: 12 | pngquant: 13 | command: bin/pngquant 14 | plugs: 15 | - home 16 | 17 | parts: 18 | pngquant: 19 | source-type: git 20 | source: https://github.com/kornelski/pngquant.git 21 | source-tag: 3.0.3 22 | plugin: rust 23 | build-packages: 24 | - gcc 25 | - libpng-dev 26 | - zlib1g-dev 27 | - liblcms2-dev 28 | stage-packages: 29 | - libpng16-16 30 | - zlib1g 31 | - liblcms2-2 32 | -------------------------------------------------------------------------------- /test/fuzzer.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include "rwpng.h" 6 | #include "libimagequant.h" 7 | #include "pngquant_opts.h" 8 | 9 | int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { 10 | if (size < 2) 11 | return 0; 12 | 13 | char img[256]; 14 | sprintf(img, "/tmp/libfuzzer.png"); 15 | 16 | FILE *fp = fopen(img, "wb"); 17 | if (!fp) 18 | return 0; 19 | fwrite(data, size, 1, fp); 20 | fclose(fp); 21 | 22 | liq_attr *attr = liq_attr_create(); 23 | png24_image tmp = {.width=0}; 24 | liq_image *input_image = NULL; 25 | read_image(attr, img, false, &tmp, &input_image, true, true, false); 26 | 27 | liq_attr_destroy(attr); 28 | if(input_image!=NULL){ 29 | liq_image_destroy(input_image); 30 | } 31 | rwpng_free_image24(&tmp); 32 | unlink(img); 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /test/img/metadata.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kornelski/pngquant/f513d98ee1d0478349d33bd103251046f3d22b53/test/img/metadata.png -------------------------------------------------------------------------------- /test/img/test.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kornelski/pngquant/f513d98ee1d0478349d33bd103251046f3d22b53/test/img/test.png -------------------------------------------------------------------------------- /test/test.c: -------------------------------------------------------------------------------- 1 | #undef NDEBUG 2 | #include 3 | #include "libimagequant.h" 4 | #include 5 | #include 6 | 7 | static char magic[] = "magic"; 8 | 9 | static void test_log_callback_function(const liq_attr *at, const char *message, void* user_info) { 10 | assert(user_info == magic); 11 | assert(message); 12 | assert(strlen(message)); 13 | } 14 | 15 | static int test_abort_callback(float progress_percent, void* user_info) { 16 | assert(user_info == magic); 17 | return 0; 18 | } 19 | 20 | static int progress_called = 0; 21 | static int test_continue_callback(float progress_percent, void* user_info) { 22 | assert(user_info == magic); 23 | progress_called++; 24 | return 1; 25 | } 26 | 27 | static void test_abort() { 28 | liq_attr *attr = liq_attr_create(); 29 | 30 | unsigned char dummy[4] = {0}; 31 | liq_image *img = liq_image_create_rgba(attr, dummy, 1, 1, 0); 32 | 33 | liq_attr_set_progress_callback(attr, test_abort_callback, magic); 34 | 35 | liq_result *res = liq_quantize_image(attr, img); 36 | assert(!res); 37 | 38 | liq_attr_destroy(attr); 39 | } 40 | 41 | static void test_zero_histogram() { 42 | liq_attr *attr = liq_attr_create(); 43 | liq_histogram *hist = liq_histogram_create(attr); 44 | assert(hist); 45 | 46 | liq_result *res; 47 | liq_error err = liq_histogram_quantize(hist, attr, &res); 48 | assert(!res); 49 | assert(err); 50 | 51 | liq_attr_destroy(attr); 52 | liq_histogram_destroy(hist); 53 | } 54 | 55 | static void test_histogram() { 56 | liq_attr *attr = liq_attr_create(); 57 | liq_histogram *hist = liq_histogram_create(attr); 58 | assert(hist); 59 | 60 | const unsigned char dummy1[4] = {255,0,255,255}; 61 | liq_image *const img1 = liq_image_create_rgba(attr, dummy1, 1, 1, 0); 62 | assert(img1); 63 | 64 | const liq_error err1 = liq_histogram_add_image(hist, attr, img1); 65 | assert(LIQ_OK == err1); 66 | 67 | const unsigned char dummy2[4] = {0,0,0,0}; 68 | liq_image *const img2 = liq_image_create_rgba(attr, dummy2, 1, 1, 0); 69 | assert(img2); 70 | liq_image_add_fixed_color(img2, (liq_color){255,255,255,255}); 71 | 72 | 73 | const liq_error err2 = liq_histogram_add_image(hist, attr, img2); 74 | assert(LIQ_OK == err2); 75 | 76 | liq_image_destroy(img1); 77 | liq_image_destroy(img2); 78 | 79 | liq_result *res; 80 | liq_error err = liq_histogram_quantize(hist, attr, &res); 81 | assert(LIQ_OK == err); 82 | assert(res); 83 | 84 | liq_attr_destroy(attr); 85 | 86 | liq_histogram_destroy(hist); 87 | 88 | const liq_palette *pal = liq_get_palette(res); 89 | assert(pal); 90 | assert(pal->count == 3); 91 | 92 | liq_result_destroy(res); 93 | } 94 | 95 | static void test_fixed_colors() { 96 | liq_attr *attr = liq_attr_create(); 97 | 98 | liq_attr_set_progress_callback(attr, test_continue_callback, magic); 99 | liq_set_log_callback(attr, test_log_callback_function, magic); 100 | 101 | unsigned char dummy[4] = {0}; 102 | liq_image *img = liq_image_create_rgba(attr, dummy, 1, 1, 0); 103 | assert(img); 104 | 105 | liq_image_add_fixed_color(img, (liq_color){0,0,0,0}); 106 | 107 | liq_result *res = liq_quantize_image(attr, img); 108 | assert(res); 109 | assert(progress_called); 110 | 111 | const liq_palette *pal = liq_get_palette(res); 112 | assert(pal); 113 | assert(pal->count == 1); 114 | 115 | liq_result_destroy(res); 116 | liq_image_destroy(img); 117 | liq_attr_destroy(attr); 118 | } 119 | 120 | static void test_fixed_colors_order() { 121 | liq_attr *attr = liq_attr_create(); 122 | 123 | unsigned char dummy[4] = {0}; 124 | liq_image *img = liq_image_create_rgba(attr, dummy, 1, 1, 0); 125 | assert(img); 126 | 127 | liq_color colors[17] = { 128 | {0,0,0,0}, {1,1,1,1}, {2,2,2,2}, {3,3,3,3}, {4,4,4,4}, {5,4,4,4}, 129 | {6,4,4,4}, {6,7,4,4}, {6,7,8,4}, {6,7,8,9}, {10,7,8,9}, {10,11,8,9}, 130 | {10,11,12,9}, {10,11,12,13}, {14,11,12,13}, {14,15,12,13}, {253,254,255,254}, 131 | }; 132 | 133 | for(int i=0; i < 17; i++) { 134 | liq_image_add_fixed_color(img, colors[i]); 135 | } 136 | 137 | liq_result *res = liq_quantize_image(attr, img); 138 | assert(res); 139 | 140 | const liq_palette *pal = liq_get_palette(res); 141 | assert(pal); 142 | assert(pal->count == 17); 143 | 144 | for(int i=0; i < 17; i++) { 145 | assert(pal->entries[i].r == colors[i].r); 146 | assert(pal->entries[i].g == colors[i].g); 147 | assert(pal->entries[i].b == colors[i].b); 148 | assert(pal->entries[i].a == colors[i].a); 149 | } 150 | 151 | liq_set_dithering_level(res, 1.0); 152 | 153 | char buf[1]; 154 | assert(LIQ_OK == liq_write_remapped_image(res, img, buf, 1)); 155 | 156 | liq_result_set_progress_callback(res, test_abort_callback, magic); 157 | assert(LIQ_ABORTED == liq_write_remapped_image(res, img, buf, 1)); 158 | 159 | liq_result_destroy(res); 160 | liq_image_destroy(img); 161 | liq_attr_destroy(attr); 162 | } 163 | 164 | int main(void) { 165 | test_fixed_colors(); 166 | test_fixed_colors_order(); 167 | test_abort(); 168 | test_histogram(); 169 | test_zero_histogram(); 170 | assert(printf("OK\n")); 171 | return 0; 172 | } 173 | -------------------------------------------------------------------------------- /test/test.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -eu 3 | set -o pipefail 4 | 5 | TESTDIR=$1 6 | IMGSRC=$TESTDIR/img 7 | TMPDIR=$(mktemp -d -t pngquantXXXXXX) 8 | BIN=$2 9 | TESTBIN=$3 10 | PATH=.:$PATH # Required, since BIN may be just 'pngquant' 11 | 12 | $BIN --version 2>&1 | fgrep 2. 13 | $BIN --help | fgrep -q "usage:" 14 | 15 | $BIN 2>/dev/null && { echo "should fail without args"; exit 1; } || true 16 | 17 | function test_overwrite() { 18 | cp "$IMGSRC/test.png" "$TMPDIR/overwritetest.png" 19 | rm -rf "$TMPDIR/overwritetest-fs8.png" "$TMPDIR/overwritetest-or8.png" 20 | 21 | $BIN "$TMPDIR/overwritetest.png" 22 | test -f "$TMPDIR/overwritetest-fs8.png" 23 | 24 | $BIN --floyd=0.5 --force "$TMPDIR/overwritetest.png" 25 | test -f "$TMPDIR/overwritetest-fs8.png" 26 | test '!' -e "$TMPDIR/overwritetest-or8.png" 27 | 28 | $BIN --nofs "$TMPDIR/overwritetest.png" 29 | test -f "$TMPDIR/overwritetest-or8.png" 30 | 31 | rm "$TMPDIR/overwritetest-or8.png" 32 | $BIN 2>&1 -nofs "$TMPDIR/overwritetest.png" | fgrep -q warning: 33 | test -f "$TMPDIR/overwritetest-or8.png" 34 | 35 | $BIN 2>/dev/null --ordered "$TMPDIR/overwritetest.png" && { echo "should refuse to overwrite"; exit 1; } || true 36 | 37 | { $BIN 2>&1 --ordered "$TMPDIR/overwritetest.png" && { echo "should refuse to overwrite"; exit 1; } || true; } | fgrep -q 'not overwriting' 38 | 39 | $BIN "$TMPDIR/overwritetest.png" -o "$TMPDIR/overwritedest.png" 40 | test -f "$TMPDIR/overwritedest.png" 41 | 42 | $BIN 2>/dev/null "$TMPDIR/overwritetest.png" -o "$TMPDIR/overwritedest.png" && { echo "should refuse to overwrite"; exit 1; } || true 43 | } 44 | 45 | function test_skip() { 46 | cp "$IMGSRC/test.png" "$TMPDIR/skiptest.png" 47 | rm -rf "$TMPDIR/shouldskip.png" 48 | 49 | $BIN 2>/dev/null "$TMPDIR/skiptest.png" -Q 100-100 -o "$TMPDIR/shouldskip.png" && { echo "should skip due to quality"; exit 1; } || RET=$? 50 | test "$RET" -eq 99 || { echo "should return 99, not $RET"; exit 1; } 51 | test '!' -e "$TMPDIR/shouldskip.png" 52 | 53 | $BIN "$TMPDIR/skiptest.png" -Q 0-50 -o "$TMPDIR/q50output.png" 54 | test -f "$TMPDIR/q50output.png" 55 | 56 | $BIN "$TMPDIR/q50output.png" --skip-if-larger -Q 0-49 -o "$TMPDIR/q49output.png" && { echo "should skip due to filesize"; exit 1; } || RET=$? 57 | test "$RET" -eq 98 || { echo "should return 98, not $RET"; exit 1; } 58 | test '!' -e "$TMPDIR/q49output.png" 59 | } 60 | 61 | function test_metadata() { 62 | cp "$IMGSRC/metadata.png" "$TMPDIR/metadatatest.png" 63 | $BIN 2>/dev/null "$TMPDIR/metadatatest.png" 64 | 65 | # This test will fail if compiled with old libpng 66 | fgrep -q '