├── .github ├── actions-rs │ └── grcov.yml ├── codecov.yml ├── main.workflow └── workflows │ └── build.yml ├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── benches ├── decode.rs └── encode.rs ├── build.rs ├── data ├── SIPI_Jelly_Beans.tiff ├── blur.py ├── octocat.png ├── octocat_blurred.png ├── wikipedia_logo.png └── wikipedia_logo_blurred.png └── src ├── ac.rs ├── base83.rs ├── dc.rs ├── error.rs ├── lib.rs └── util.rs /.github/actions-rs/grcov.yml: -------------------------------------------------------------------------------- 1 | output-path: ./coverage.xml 2 | -------------------------------------------------------------------------------- /.github/codecov.yml: -------------------------------------------------------------------------------- 1 | github_checks: 2 | annotations: false 3 | 4 | coverage: 5 | status: 6 | project: 7 | default: 8 | informational: true 9 | patch: 10 | default: 11 | informational: true 12 | -------------------------------------------------------------------------------- /.github/main.workflow: -------------------------------------------------------------------------------- 1 | workflow "Test and Publish" { 2 | on = "push" 3 | resolves = ["Release"] 4 | } 5 | 6 | action "Fmt Check and Test" { 7 | uses = "icepuma/rust-action@master" 8 | args = "cargo fmt -- --check && cargo clippy -- -Dwarnings && cargo test" 9 | } 10 | 11 | action "Tag" { 12 | uses = "actions/bin/filter@master" 13 | needs = ["Fmt Check and Test"] 14 | args = "tag v*" 15 | } 16 | 17 | action "Release" { 18 | uses = "icepuma/rust-action@master" 19 | needs = ["Tag"] 20 | args = "cargo login $CARGO_TOKEN && cargo publish" 21 | secrets = ["CARGO_TOKEN"] 22 | } 23 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build 2 | on: 3 | push: 4 | branches: 5 | - main 6 | pull_request: 7 | 8 | env: 9 | CARGO_INCREMENTAL: 0 10 | CARGO_REGISTRIES_CRATES_IO_PROTOCOL: sparse 11 | 12 | concurrency: 13 | group: ${{ github.workflow }}-${{ github.ref }} 14 | cancel-in-progress: true 15 | 16 | jobs: 17 | build_and_test: 18 | name: cargo test 19 | runs-on: ubuntu-latest 20 | env: 21 | RUSTFLAGS: -D warnings 22 | strategy: 23 | fail-fast: false 24 | matrix: 25 | toolchain: ["stable", "beta"] 26 | coverage: [false] 27 | include: 28 | - toolchain: "nightly" 29 | coverage: true 30 | steps: 31 | - name: Checkout repository 32 | uses: actions/checkout@v2 33 | 34 | - uses: actions-rs/toolchain@v1 35 | with: 36 | toolchain: ${{ matrix.toolchain }} 37 | override: true 38 | 39 | - name: Configure CI cache 40 | uses: Swatinem/rust-cache@v2 41 | 42 | - name: Build 43 | uses: actions-rs/cargo@v1 44 | with: 45 | command: build 46 | args: --all-targets 47 | 48 | - name: Run tests with default features 49 | uses: actions-rs/cargo@v1 50 | if: ${{ !matrix.coverage }} 51 | with: 52 | command: test 53 | args: --all-targets --no-fail-fast 54 | 55 | - name: Run tests with all features 56 | uses: actions-rs/cargo@v1 57 | if: ${{ !matrix.coverage }} 58 | with: 59 | command: test 60 | args: --all-targets --no-fail-fast --all-features 61 | 62 | - name: Run doc tests 63 | uses: actions-rs/cargo@v1 64 | if: ${{ !matrix.coverage }} 65 | with: 66 | command: test 67 | args: --doc --no-fail-fast --all-features 68 | 69 | - name: Run tests 70 | uses: actions-rs/cargo@v1 71 | if: ${{ matrix.coverage }} 72 | with: 73 | command: test 74 | args: --all-targets --no-fail-fast --all-features 75 | env: 76 | CARGO_INCREMENTAL: '0' 77 | RUSTFLAGS: '-Zprofile -Ccodegen-units=1 -Cinline-threshold=0 -Clink-dead-code -Coverflow-checks=off -Cpanic=abort -Zpanic_abort_tests' 78 | RUSTDOCFLAGS: '-Zprofile -Ccodegen-units=1 -Cinline-threshold=0 -Clink-dead-code -Coverflow-checks=off -Cpanic=abort -Zpanic_abort_tests' 79 | 80 | - name: Generate code coverage 81 | uses: actions-rs/grcov@v0.1 82 | if: ${{ matrix.coverage }} 83 | 84 | - name: Upload coverage reports to Codecov with GitHub Action 85 | uses: codecov/codecov-action@v3 86 | if: ${{ matrix.coverage }} 87 | 88 | rustfmt: 89 | name: rustfmt 90 | runs-on: ubuntu-latest 91 | steps: 92 | - name: Checkout repository 93 | uses: actions/checkout@v2 94 | 95 | - name: Setup Rust toolchain 96 | run: rustup install stable 97 | 98 | - name: Check code format 99 | uses: actions-rs/cargo@v1 100 | with: 101 | command: fmt 102 | args: -- --check 103 | 104 | clippy: 105 | name: clippy 106 | runs-on: ubuntu-latest 107 | steps: 108 | - name: Checkout repository 109 | uses: actions/checkout@v2 110 | 111 | - name: Setup Rust toolchain 112 | run: rustup install stable 113 | 114 | - name: Setup CI cache 115 | uses: Swatinem/rust-cache@v2 116 | 117 | - name: Run clippy lints 118 | uses: actions-rs/cargo@v1 119 | with: 120 | command: clippy 121 | 122 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | 4 | Cargo.lock 5 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "blurhash" 3 | description = "A pure Rust implementation of blurhash" 4 | documentation = "https://docs.rs/blurhash" 5 | repository = "https://github.com/whisperfish/blurhash-rs" 6 | readme = "README.md" 7 | keywords = ["blurhash", "image"] 8 | license = "Apache-2.0/MIT" 9 | version = "0.2.3" 10 | authors = ["Ruben De Smet ", "Raincal "] 11 | edition = "2018" 12 | 13 | [dependencies] 14 | image = { version = ">= 0.23, <= 0.25", optional = true } 15 | gdk-pixbuf = { version = ">= 0.18, <= 0.20", optional = true } 16 | 17 | [dev-dependencies] 18 | image = ">= 0.23, <= 0.25" 19 | criterion = "0.5" 20 | proptest = "1" 21 | 22 | [features] 23 | default = ["fast-linear-to-srgb"] 24 | image = [ "dep:image" ] 25 | gdk-pixbuf = [ "dep:gdk-pixbuf" ] 26 | fast-linear-to-srgb = [] 27 | 28 | [[bench]] 29 | name = "decode" 30 | harness = false 31 | 32 | [[bench]] 33 | name = "encode" 34 | harness = false 35 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Raincal 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # blurhash-rs 2 | 3 | ![CI Build](https://github.com/whisperfish/blurhash-rs/workflows/Build/badge.svg) 4 | [![Crates.io](https://img.shields.io/crates/v/blurhash.svg)](https://crates.io/crates/blurhash) 5 | [![Crates.io](https://img.shields.io/crates/l/blurhash.svg)](https://crates.io/crates/blurhash) 6 | 7 | > A pure Rust implementation of [Blurhash](https://github.com/woltapp/blurhash). 8 | 9 | Blurhash is an algorithm written by [Dag Ågren](https://github.com/DagAgren) for [Wolt (woltapp/blurhash)](https://github.com/woltapp/blurhash) that encodes an image into a short (~20-30 byte) ASCII string. When you decode the string back into an image, you get a gradient of colors that represent the original image. This can be useful for scenarios where you want an image placeholder before loading, or even to censor the contents of an image [a la Mastodon](https://blog.joinmastodon.org/2019/05/improving-support-for-adult-content-on-mastodon/). 10 | 11 | ## 🚴 Usage 12 | 13 | Add `blurhash` to your `Cargo.toml`: 14 | 15 | ```toml 16 | [dependencies] 17 | blurhash = "0.2.3" 18 | ``` 19 | 20 | By default, the `fast-linear-to-srgb` is enabled. 21 | This improves decoding performance by about 60%, but has a memory overhead of 8KB. 22 | If this overhead is problematic, you can disable it by instead specifying the following to your `Cargo.toml`: 23 | 24 | ```toml 25 | [dependencies] 26 | blurhash = { version = "0.2.3", default-features = false } 27 | ``` 28 | 29 | ### Encoding 30 | ```rust 31 | use blurhash::encode; 32 | use image::GenericImageView; 33 | 34 | fn main() { 35 | // Add image to your Cargo.toml 36 | let img = image::open("octocat.png").unwrap(); 37 | let (width, height) = img.dimensions(); 38 | let blurhash = encode(4, 3, width, height, &img.to_rgba().into_vec()); 39 | } 40 | ``` 41 | 42 | ### Decoding 43 | ```rust 44 | use blurhash::decode; 45 | 46 | let pixels = decode("LBAdAqof00WCqZj[PDay0.WB}pof", 50, 50, 1.0); 47 | ``` 48 | 49 | ## Licence 50 | 51 | Licensed under either of 52 | 53 | * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 54 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 55 | -------------------------------------------------------------------------------- /benches/decode.rs: -------------------------------------------------------------------------------- 1 | use criterion::{black_box, criterion_group, criterion_main, BenchmarkId, Criterion}; 2 | 3 | pub fn criterion_benchmark(c: &mut Criterion) { 4 | let cases = [ 5 | "LEHLk~WB2yk8pyo0adR*.7kCMdnj", 6 | "LGF5]+Yk^6#M@-5c,1J5@[or[Q6.", 7 | "L6Pj0^jE.AyE_3t7t7R**0o#DgR4", 8 | "LKO2:N%2Tw=w]~RBVZRi};RPxuwH", 9 | ]; 10 | 11 | for case in cases { 12 | for size in [50, 100, 200, 256, 500, 512] { 13 | c.bench_with_input( 14 | BenchmarkId::new(format!("decode {}", case), size), 15 | &(case, size), 16 | |b, &(case, size)| { 17 | b.iter(|| { 18 | let case = black_box(case); 19 | blurhash::decode(case, size, size, 1.0).unwrap() 20 | }) 21 | }, 22 | ); 23 | 24 | c.bench_with_input( 25 | BenchmarkId::new(format!("decode_into {}", case), size), 26 | &(case, size), 27 | |b, &(case, size)| { 28 | let mut buf = vec![0u8; size as usize * size as usize * 4]; 29 | b.iter(|| { 30 | let case = black_box(case); 31 | blurhash::decode_into(&mut buf, case, size, size, 1.0).unwrap() 32 | }) 33 | }, 34 | ); 35 | } 36 | } 37 | } 38 | 39 | criterion_group!(benches, criterion_benchmark); 40 | criterion_main!(benches); 41 | -------------------------------------------------------------------------------- /benches/encode.rs: -------------------------------------------------------------------------------- 1 | use criterion::{black_box, criterion_group, criterion_main, Criterion}; 2 | use image::GenericImageView; 3 | 4 | pub fn lenna(c: &mut Criterion) { 5 | for case in ["data/SIPI_Jelly_Beans.tiff", "data/octocat.png"] { 6 | let img = image::open(case).unwrap(); 7 | 8 | let (width, height) = img.dimensions(); 9 | let img = img.to_rgba8(); 10 | 11 | c.bench_function(&format!("encode {}", case), |b| { 12 | b.iter(|| blurhash::encode(4, 3, width, height, black_box(&img)).unwrap()); 13 | }); 14 | } 15 | } 16 | 17 | criterion_group!(benches, lenna); 18 | criterion_main!(benches); 19 | -------------------------------------------------------------------------------- /build.rs: -------------------------------------------------------------------------------- 1 | use std::io::Write; 2 | 3 | const LINEAR_TO_SRGB_LOOKUP_SIZE: usize = 8192; 4 | 5 | fn linear_to_srgb(value: f32) -> u8 { 6 | let v = value.clamp(0., 1.); 7 | if v <= 0.003_130_8 { 8 | (v * 12.92 * 255. + 0.5).round() as u8 9 | } else { 10 | ((1.055 * 255.) * f32::powf(v, 1. / 2.4) - (0.055 * 255. - 0.5)).round() as u8 11 | } 12 | } 13 | 14 | fn generate_linear_to_srgb_lookup() -> [u8; LINEAR_TO_SRGB_LOOKUP_SIZE] { 15 | let mut table = [0u8; LINEAR_TO_SRGB_LOOKUP_SIZE]; 16 | for i in 0..table.len() { 17 | let float = i as f32 / (table.len() - 1) as f32; 18 | table[i] = linear_to_srgb(float); 19 | } 20 | table 21 | } 22 | 23 | /// srgb 0-255 integer to linear 0.0-1.0 floating point conversion. 24 | pub fn srgb_to_linear(value: u8) -> f32 { 25 | let v = value as f32 / 255.; 26 | if v <= 0.04045 { 27 | v / 12.92 28 | } else { 29 | f32::powf((v + 0.055) / 1.055, 2.4) 30 | } 31 | } 32 | 33 | fn generate_srgb_lookup() -> [f32; 256] { 34 | let mut table = [0f32; 256]; 35 | for (i, val) in table.iter_mut().enumerate() { 36 | *val = srgb_to_linear(i as u8); 37 | } 38 | table 39 | } 40 | 41 | fn write_srgb(f: &mut std::fs::File) { 42 | writeln!( 43 | f, 44 | " 45 | static SRGB_LOOKUP: [f32; 256] = {:?}; 46 | #[cfg(feature = \"fast-linear-to-srgb\")] 47 | const LINEAR_TO_SRGB_LOOKUP_SIZE: usize = {}; 48 | #[cfg(feature = \"fast-linear-to-srgb\")] 49 | static LINEAR_TO_SRGB_LOOKUP: [u8; LINEAR_TO_SRGB_LOOKUP_SIZE] = {:?}; 50 | ", 51 | generate_srgb_lookup(), 52 | LINEAR_TO_SRGB_LOOKUP_SIZE, 53 | generate_linear_to_srgb_lookup() 54 | ) 55 | .unwrap(); 56 | } 57 | 58 | fn write_base83(f: &mut std::fs::File) { 59 | const CHARACTERS: &[u8; 83] = 60 | b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz#$%*+,-.:;=?@[]^_{|}~"; 61 | writeln!(f, "const CHARACTERS: [u8; 83] = {:?};", CHARACTERS).unwrap(); 62 | 63 | let max_plus_one = CHARACTERS.iter().max().unwrap() + 1; 64 | let mut inv_map: [u8; 256] = [max_plus_one; 256]; 65 | for (i, &c) in CHARACTERS.iter().enumerate() { 66 | inv_map[c as usize] = i as u8; 67 | } 68 | writeln!( 69 | f, 70 | "const CHARACTERS_INV: [u8; {max_plus_one}] = {:?};", 71 | &inv_map[0..max_plus_one as usize] 72 | ) 73 | .unwrap(); 74 | writeln!(f, "const CHARACTERS_INV_INVALID: u8 = {};", max_plus_one).unwrap(); 75 | } 76 | 77 | fn main() { 78 | let out_dir = std::env::var("OUT_DIR").unwrap(); 79 | let out_dir = std::path::PathBuf::from(out_dir); 80 | 81 | let mut f = std::fs::File::create(out_dir.join("srgb_lookup.rs")).unwrap(); 82 | write_srgb(&mut f); 83 | 84 | let mut f = std::fs::File::create(out_dir.join("base83_lookup.rs")).unwrap(); 85 | write_base83(&mut f); 86 | } 87 | -------------------------------------------------------------------------------- /data/SIPI_Jelly_Beans.tiff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/whisperfish/blurhash-rs/2135e101377e514266358b3e67adab37e736bb8a/data/SIPI_Jelly_Beans.tiff -------------------------------------------------------------------------------- /data/blur.py: -------------------------------------------------------------------------------- 1 | # Blur the test images using the official blurhash-python package. 2 | # The results are used as reference images in the tests of blurhash-rs. 3 | 4 | import blurhash 5 | from os import listdir 6 | from PIL import Image 7 | 8 | images = [f for f in listdir(".") if "png" in f and not "blurred" in f] 9 | 10 | for path in images: 11 | with Image.open(path) as image: 12 | hash = blurhash.encode(image, x_components=4, y_components=3) 13 | width, height = image.size 14 | 15 | result = blurhash.decode(hash, width, height, mode=blurhash.PixelMode.RGBA) 16 | result.save(path.split(".")[0] + "_blurred.png") 17 | -------------------------------------------------------------------------------- /data/octocat.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/whisperfish/blurhash-rs/2135e101377e514266358b3e67adab37e736bb8a/data/octocat.png -------------------------------------------------------------------------------- /data/octocat_blurred.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/whisperfish/blurhash-rs/2135e101377e514266358b3e67adab37e736bb8a/data/octocat_blurred.png -------------------------------------------------------------------------------- /data/wikipedia_logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/whisperfish/blurhash-rs/2135e101377e514266358b3e67adab37e736bb8a/data/wikipedia_logo.png -------------------------------------------------------------------------------- /data/wikipedia_logo_blurred.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/whisperfish/blurhash-rs/2135e101377e514266358b3e67adab37e736bb8a/data/wikipedia_logo_blurred.png -------------------------------------------------------------------------------- /src/ac.rs: -------------------------------------------------------------------------------- 1 | use super::util::sign_pow; 2 | 3 | pub fn encode(value: [f32; 3], maximum_value: f32) -> u32 { 4 | let quant_r = i32::max( 5 | 0, 6 | i32::min( 7 | 18, 8 | f32::floor(sign_pow(value[0] / maximum_value, 0.5) * 9. + 9.5) as i32, 9 | ), 10 | ); 11 | let quant_g = i32::max( 12 | 0, 13 | i32::min( 14 | 18, 15 | f32::floor(sign_pow(value[1] / maximum_value, 0.5) * 9. + 9.5) as i32, 16 | ), 17 | ); 18 | let quant_b = i32::max( 19 | 0, 20 | i32::min( 21 | 18, 22 | f32::floor(sign_pow(value[2] / maximum_value, 0.5) * 9. + 9.5) as i32, 23 | ), 24 | ); 25 | 26 | (quant_r * 19 * 19 + quant_g * 19 + quant_b) as u32 27 | } 28 | 29 | pub fn decode(value: u32, maximum_value: f32) -> [f32; 3] { 30 | let quant_r = f32::floor(value as f32 / (19. * 19.)); 31 | let quant_g = f32::floor(value as f32 / 19.) % 19.; 32 | let quant_b = value as f32 % 19.; 33 | 34 | [ 35 | sign_pow((quant_r - 9.) / 9., 2.0) * maximum_value, 36 | sign_pow((quant_g - 9.) / 9., 2.0) * maximum_value, 37 | sign_pow((quant_b - 9.) / 9., 2.0) * maximum_value, 38 | ] 39 | } 40 | -------------------------------------------------------------------------------- /src/base83.rs: -------------------------------------------------------------------------------- 1 | use crate::Error; 2 | 3 | include!(concat!(env!("OUT_DIR"), "/base83_lookup.rs")); 4 | 5 | pub fn encode_into(value: u32, length: u32, s: &mut String) { 6 | for i in 1..=length { 7 | let digit: u32 = (value / u32::pow(83, length - i)) % 83; 8 | s.push(CHARACTERS[digit as usize] as char); 9 | } 10 | } 11 | 12 | pub fn decode(str: &str) -> Result { 13 | // log_83(2^64) = 10.03 14 | if str.len() > 10 { 15 | panic!("base83::decode can only process strings up to 10 characters"); 16 | } 17 | let mut value = 0; 18 | 19 | for byte in str.as_bytes() { 20 | if *byte as usize >= CHARACTERS_INV.len() { 21 | return Err(Error::InvalidBase83(*byte)); 22 | } 23 | let digit = CHARACTERS_INV[*byte as usize]; 24 | if digit == CHARACTERS_INV_INVALID { 25 | return Err(Error::InvalidBase83(*byte)); 26 | } 27 | value = value * 83 + digit as u64; 28 | } 29 | 30 | Ok(value) 31 | } 32 | 33 | #[cfg(test)] 34 | mod tests { 35 | use super::{decode, encode_into}; 36 | 37 | fn encode(value: u32, length: u32) -> String { 38 | let mut s = String::new(); 39 | encode_into(value, length, &mut s); 40 | s 41 | } 42 | 43 | #[test] 44 | fn encode83() { 45 | let str = encode(6869, 2); 46 | assert_eq!(str, "~$"); 47 | } 48 | 49 | #[test] 50 | fn decode83() { 51 | let v = decode("~$").unwrap(); 52 | assert_eq!(v, 6869); 53 | } 54 | 55 | #[test] 56 | fn decode83_too_large() { 57 | assert!(decode("€").is_err()); 58 | } 59 | 60 | #[test] 61 | #[should_panic] 62 | fn decode83_too_long() { 63 | let _ = decode("~$aaaaaaaaa"); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/dc.rs: -------------------------------------------------------------------------------- 1 | use super::util::{linear_to_srgb, srgb_to_linear}; 2 | 3 | pub fn encode(value: [f32; 3]) -> u32 { 4 | let rounded_r = linear_to_srgb(value[0]) as u32; 5 | let rounded_g = linear_to_srgb(value[1]) as u32; 6 | let rounded_b = linear_to_srgb(value[2]) as u32; 7 | (rounded_r << 16) + (rounded_g << 8) + rounded_b 8 | } 9 | 10 | pub fn decode(value: u32) -> [f32; 3] { 11 | let int_r = (value >> 16) & 255; 12 | let int_g = (value >> 8) & 255; 13 | let int_b = value & 255; 14 | 15 | [ 16 | srgb_to_linear(int_r as u8), 17 | srgb_to_linear(int_g as u8), 18 | srgb_to_linear(int_b as u8), 19 | ] 20 | } 21 | 22 | #[cfg(test)] 23 | mod tests { 24 | use super::*; 25 | 26 | #[test] 27 | fn overflow_not_panicing() { 28 | let _ = decode(1 << 17); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/error.rs: -------------------------------------------------------------------------------- 1 | use std::fmt; 2 | 3 | #[derive(Debug)] 4 | pub enum Error { 5 | HashTooShort, 6 | LengthMismatch { expected: usize, actual: usize }, 7 | InvalidAscii, 8 | InvalidBase83(u8), 9 | ComponentsOutOfRange, 10 | } 11 | 12 | impl fmt::Display for Error { 13 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 14 | let message = match self { 15 | Error::HashTooShort => "blurhash must be at least 6 characters long".to_string(), 16 | Error::LengthMismatch { expected, actual } => format!( 17 | "blurhash length mismatch: length is {} but it should be {}", 18 | actual, expected 19 | ), 20 | Error::InvalidBase83(byte) => format!("Invalid base83 character: {:?}", *byte as char), 21 | Error::InvalidAscii => "blurhash must be valid ASCII".into(), 22 | Error::ComponentsOutOfRange => "blurhash must have between 1 and 9 components".into(), 23 | }; 24 | write!(f, "{}", message) 25 | } 26 | } 27 | 28 | impl std::error::Error for Error {} 29 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! A pure Rust implementation of [woltapp/blurhash][1]. 2 | //! 3 | //! ### Encoding 4 | //! 5 | //! ``` 6 | //! use blurhash::encode; 7 | //! use image::{GenericImageView, EncodableLayout}; 8 | //! 9 | //! let img = image::open("data/octocat.png").unwrap(); 10 | //! let (width, height) = img.dimensions(); 11 | //! let blurhash = encode(4, 3, width, height, img.to_rgba8().as_bytes()).unwrap(); 12 | //! 13 | //! assert_eq!(blurhash, "LNAdAqj[00aymkj[TKay9}ay-Sj["); 14 | //! ``` 15 | //! 16 | //! ### Decoding 17 | //! 18 | //! ```no_run 19 | //! use blurhash::decode; 20 | //! 21 | //! let pixels = decode("LBAdAqof00WCqZj[PDay0.WB}pof", 50, 50, 1.0); 22 | //! ``` 23 | //! [1]: https://github.com/woltapp/blurhash 24 | mod ac; 25 | mod base83; 26 | mod dc; 27 | mod error; 28 | mod util; 29 | 30 | pub use error::Error; 31 | 32 | use std::f32::consts::PI; 33 | use util::{linear_to_srgb, srgb_to_linear}; 34 | 35 | /// Calculates the blurhash for an image using the given x and y component counts. 36 | pub fn encode( 37 | components_x: u32, 38 | components_y: u32, 39 | width: u32, 40 | height: u32, 41 | rgba_image: &[u8], 42 | ) -> Result { 43 | if !(1..=9).contains(&components_x) || !(1..=9).contains(&components_y) { 44 | return Err(Error::ComponentsOutOfRange); 45 | } 46 | 47 | let mut factors: Vec<[f32; 3]> = 48 | Vec::with_capacity(components_x as usize * components_y as usize); 49 | 50 | for y in 0..components_y { 51 | for x in 0..components_x { 52 | let factor = multiply_basis_function(x, y, width, height, rgba_image); 53 | factors.push(factor); 54 | } 55 | } 56 | 57 | let dc = factors[0]; 58 | let ac = &factors[1..]; 59 | 60 | let mut blurhash = String::with_capacity( 61 | // 1 byte for size flag 62 | 1 63 | // 1 byte for maximum value 64 | + 1 65 | // 4 bytes for DC 66 | + 4 67 | // 2 bytes for each AC 68 | + 2 * ac.len(), 69 | ); 70 | 71 | let size_flag = (components_x - 1) + (components_y - 1) * 9; 72 | base83::encode_into(size_flag, 1, &mut blurhash); 73 | 74 | let maximum_value: f32; 75 | if !ac.is_empty() { 76 | let actualmaximum_value = ac 77 | .iter() 78 | .flatten() 79 | .map(|x| f32::abs(*x)) 80 | .reduce(f32::max) 81 | .unwrap_or(0.0); 82 | 83 | let quantised_maximum_value = 84 | f32::floor(actualmaximum_value * 166. - 0.5).clamp(0., 82.) as u32; 85 | 86 | maximum_value = (quantised_maximum_value + 1) as f32 / 166.; 87 | base83::encode_into(quantised_maximum_value, 1, &mut blurhash); 88 | } else { 89 | maximum_value = 1.; 90 | base83::encode_into(0, 1, &mut blurhash); 91 | } 92 | 93 | base83::encode_into(dc::encode(dc), 4, &mut blurhash); 94 | 95 | for i in 0..components_y * components_x - 1 { 96 | base83::encode_into(ac::encode(ac[i as usize], maximum_value), 2, &mut blurhash); 97 | } 98 | 99 | Ok(blurhash) 100 | } 101 | 102 | fn multiply_basis_function( 103 | component_x: u32, 104 | component_y: u32, 105 | width: u32, 106 | height: u32, 107 | rgb: &[u8], 108 | ) -> [f32; 3] { 109 | let mut r = 0.; 110 | let mut g = 0.; 111 | let mut b = 0.; 112 | let normalisation = match (component_x, component_y) { 113 | (0, 0) => 1., 114 | _ => 2., 115 | }; 116 | 117 | let bytes_per_row = width * 4; 118 | 119 | let pi_cx_over_width = PI * component_x as f32 / width as f32; 120 | let pi_cy_over_height = PI * component_y as f32 / height as f32; 121 | 122 | let mut cos_pi_cx_over_width = vec![0.; width as usize]; 123 | for x in 0..width { 124 | cos_pi_cx_over_width[x as usize] = f32::cos(pi_cx_over_width * x as f32); 125 | } 126 | 127 | let mut cos_pi_cy_over_height = vec![0.; height as usize]; 128 | for y in 0..height { 129 | cos_pi_cy_over_height[y as usize] = f32::cos(pi_cy_over_height * y as f32); 130 | } 131 | 132 | for y in 0..height { 133 | for x in 0..width { 134 | let basis = cos_pi_cx_over_width[x as usize] * cos_pi_cy_over_height[y as usize]; 135 | r += basis * srgb_to_linear(rgb[(4 * x + y * bytes_per_row) as usize]); 136 | g += basis * srgb_to_linear(rgb[(4 * x + 1 + y * bytes_per_row) as usize]); 137 | b += basis * srgb_to_linear(rgb[(4 * x + 2 + y * bytes_per_row) as usize]); 138 | } 139 | } 140 | 141 | let scale = normalisation / (width * height) as f32; 142 | 143 | [r * scale, g * scale, b * scale] 144 | } 145 | 146 | /// Decodes the given blurhash to an image of the specified size into an existing buffer. 147 | /// 148 | /// The punch parameter can be used to de- or increase the contrast of the 149 | /// resulting image. 150 | pub fn decode_into( 151 | pixels: &mut [u8], 152 | blurhash: &str, 153 | width: u32, 154 | height: u32, 155 | punch: f32, 156 | ) -> Result<(), Error> { 157 | if !blurhash.is_ascii() { 158 | return Err(Error::InvalidAscii); 159 | } 160 | 161 | let (num_x, num_y) = components(blurhash)?; 162 | 163 | assert_eq!( 164 | (width * height * 4) as usize, 165 | pixels.len(), 166 | "buffer length equals 4 * width * height" 167 | ); 168 | 169 | let quantised_maximum_value = base83::decode(&blurhash[1..2])?; 170 | let maximum_value = (quantised_maximum_value + 1) as f32 / 166.; 171 | 172 | let mut colors = vec![[0.; 3]; num_x * num_y]; 173 | 174 | for i in 0..colors.len() { 175 | if i == 0 { 176 | let value = base83::decode(&blurhash[2..6])?; 177 | colors[i] = dc::decode(value as u32); 178 | } else { 179 | let value = base83::decode(&blurhash[4 + i * 2..6 + i * 2])?; 180 | colors[i] = ac::decode(value as u32, maximum_value * punch); 181 | } 182 | } 183 | 184 | let colors: Vec<_> = colors.chunks(num_x).collect(); 185 | 186 | let bytes_per_row = width as usize * 4; 187 | 188 | let pi_over_height = PI / height as f32; 189 | let pi_over_width = PI / width as f32; 190 | 191 | // Precompute the cosines 192 | let mut cos_i_pi_x_over_width = vec![0.; width as usize * num_x]; 193 | let mut cos_j_pi_y_over_height = vec![0.; height as usize * num_y]; 194 | 195 | for x in 0..width { 196 | let pi_x_over_width = x as f32 * pi_over_width; 197 | for i in 0..num_x { 198 | cos_i_pi_x_over_width[x as usize * num_x + i] = f32::cos(pi_x_over_width * i as f32); 199 | } 200 | } 201 | 202 | for y in 0..height { 203 | let pi_y_over_height = y as f32 * pi_over_height; 204 | for j in 0..num_y { 205 | cos_j_pi_y_over_height[y as usize * num_y + j] = f32::cos(j as f32 * pi_y_over_height); 206 | } 207 | } 208 | 209 | // Hint to the optimizer that the length of the slices is correct 210 | assert!(height as usize * num_y == cos_j_pi_y_over_height.len()); 211 | assert!(width as usize * num_x == cos_i_pi_x_over_width.len()); 212 | 213 | for y in 0..height as usize { 214 | let pixels = &mut pixels[y * bytes_per_row..][..bytes_per_row]; 215 | 216 | // More optimizer hints. 217 | assert!(y * num_y + num_y <= cos_j_pi_y_over_height.len()); 218 | 219 | for x in 0..width as usize { 220 | let mut pixel = [0.; 3]; 221 | 222 | let cos_j_pi_y_over_height = &cos_j_pi_y_over_height[y * num_y..][..num_y]; 223 | let cos_i_pi_x_over_width = &cos_i_pi_x_over_width[x * num_x..][..num_x]; 224 | 225 | assert_eq!(cos_j_pi_y_over_height.len(), colors.len()); 226 | assert_eq!(cos_j_pi_y_over_height.len(), num_y); 227 | 228 | for (cos_j, colors) in cos_j_pi_y_over_height.iter().zip(colors.iter()) { 229 | assert_eq!(cos_i_pi_x_over_width.len(), colors.len()); 230 | assert_eq!(cos_i_pi_x_over_width.len(), num_x); 231 | 232 | for (cos_i, color) in cos_i_pi_x_over_width.iter().zip(colors.iter()) { 233 | let basis = cos_i * cos_j; 234 | 235 | pixel[0] += color[0] * basis; 236 | pixel[1] += color[1] * basis; 237 | pixel[2] += color[2] * basis; 238 | } 239 | } 240 | 241 | let int_r = linear_to_srgb(pixel[0]); 242 | let int_g = linear_to_srgb(pixel[1]); 243 | let int_b = linear_to_srgb(pixel[2]); 244 | 245 | let pixels = &mut pixels[4 * x..][..4]; 246 | 247 | pixels[0] = int_r; 248 | pixels[1] = int_g; 249 | pixels[2] = int_b; 250 | pixels[3] = 255u8; 251 | } 252 | } 253 | Ok(()) 254 | } 255 | 256 | /// Decodes the given blurhash to an image of the specified size. 257 | /// 258 | /// The punch parameter can be used to de- or increase the contrast of the 259 | /// resulting image. 260 | pub fn decode(blurhash: &str, width: u32, height: u32, punch: f32) -> Result, Error> { 261 | let bytes_per_row = width * 4; 262 | let mut pixels = vec![0; (bytes_per_row * height) as usize]; 263 | decode_into(&mut pixels, blurhash, width, height, punch).map(|()| pixels) 264 | } 265 | 266 | fn components(blurhash: &str) -> Result<(usize, usize), Error> { 267 | if blurhash.len() < 6 { 268 | return Err(Error::HashTooShort); 269 | } 270 | 271 | let size_flag = base83::decode(&blurhash[0..1])?; 272 | let num_y = (f32::floor(size_flag as f32 / 9.) + 1.) as usize; 273 | let num_x = ((size_flag % 9) + 1) as usize; 274 | 275 | let expected = 4 + 2 * num_x * num_y; 276 | if blurhash.len() != expected { 277 | return Err(Error::LengthMismatch { 278 | expected, 279 | actual: blurhash.len(), 280 | }); 281 | } 282 | 283 | Ok((num_x, num_y)) 284 | } 285 | 286 | /// Calculates the blurhash for an [DynamicImage][image::DynamicImage] using the given x and y component counts. 287 | #[cfg(feature = "image")] 288 | pub fn encode_image( 289 | components_x: u32, 290 | components_y: u32, 291 | image: &image::RgbaImage, 292 | ) -> Result { 293 | use image::EncodableLayout; 294 | encode( 295 | components_x, 296 | components_y, 297 | image.width(), 298 | image.height(), 299 | image.as_bytes(), 300 | ) 301 | } 302 | 303 | /// Calculates the blurhash for an [Pixbuf][gdk_pixbuf::Pixbuf] using the given x and y component counts. 304 | /// 305 | /// Will panic if either the width or height of the image is negative. 306 | #[cfg(feature = "gdk-pixbuf")] 307 | pub fn encode_pixbuf( 308 | components_x: u32, 309 | components_y: u32, 310 | image: &gdk_pixbuf::Pixbuf, 311 | ) -> Result { 312 | use std::convert::TryInto; 313 | encode( 314 | components_x, 315 | components_y, 316 | image.width().try_into().expect("non-negative width"), 317 | image.height().try_into().expect("non-negative height"), 318 | &image.read_pixel_bytes(), 319 | ) 320 | } 321 | 322 | /// Decodes the given blurhash to an image of the specified size. 323 | /// 324 | /// The punch parameter can be used to de- or increase the contrast of the 325 | /// resulting image. 326 | #[cfg(feature = "image")] 327 | pub fn decode_image( 328 | blurhash: &str, 329 | width: u32, 330 | height: u32, 331 | punch: f32, 332 | ) -> Result { 333 | let bytes = decode(blurhash, width, height, punch)?; 334 | // Save to unwrap as `decode` (if successfull) always returns a buffer of size `4 * width * height`, which is exactly 335 | // the amount of bytes required to construct the `RgbaImage`. 336 | let buffer = image::RgbaImage::from_raw(width, height, bytes).expect("decoded image too small"); 337 | Ok(buffer) 338 | } 339 | 340 | /// Decodes the given blurhash to an [Pixbuf][gdk_pixbuf::Pixbuf] of the specified size. 341 | /// 342 | /// The punch parameter can be used to de- or increase the contrast of the 343 | /// resulting image. 344 | /// Will panic if the width or height does not fit in i32. 345 | #[cfg(feature = "gdk-pixbuf")] 346 | pub fn decode_pixbuf( 347 | blurhash: &str, 348 | width: u32, 349 | height: u32, 350 | punch: f32, 351 | ) -> Result { 352 | use std::convert::TryInto; 353 | let bytes = decode(blurhash, width, height, punch)?; 354 | let width = width.try_into().expect("width fits in i32"); 355 | let height = height.try_into().expect("height fits in i32"); 356 | let buffer = gdk_pixbuf::Pixbuf::from_bytes( 357 | &gdk_pixbuf::glib::Bytes::from_owned(bytes), 358 | gdk_pixbuf::Colorspace::Rgb, 359 | true, 360 | 8, 361 | width, 362 | height, 363 | 4 * width, 364 | ); 365 | Ok(buffer) 366 | } 367 | 368 | #[cfg(test)] 369 | mod tests { 370 | use super::*; 371 | use image::{EncodableLayout, GenericImageView}; 372 | use proptest::prelude::*; 373 | 374 | #[test] 375 | fn decode_blurhash() { 376 | let img = image::open("data/octocat.png").unwrap(); 377 | let (width, height) = img.dimensions(); 378 | 379 | let blurhash = encode(4, 3, width, height, img.to_rgba8().as_bytes()).unwrap(); 380 | let img = decode(&blurhash, width, height, 1.0).unwrap(); 381 | 382 | assert_eq!(img[0..5], [1, 1, 1, 255, 1]); 383 | } 384 | 385 | #[test] 386 | fn decode_non_ascii() { 387 | assert!(matches!( 388 | decode("ͱZ", 50, 50, 1.0), 389 | Err(Error::InvalidAscii) 390 | )); 391 | } 392 | 393 | #[test] 394 | fn test_jelly_beans() { 395 | use image::{EncodableLayout, GenericImageView}; 396 | 397 | let img = image::open("data/octocat.png").unwrap(); 398 | let (width, height) = img.dimensions(); 399 | let blurhash = encode(4, 3, width, height, img.to_rgba8().as_bytes()).unwrap(); 400 | 401 | assert_eq!(blurhash, "LNAdAqj[00aymkj[TKay9}ay-Sj["); 402 | } 403 | 404 | #[test] 405 | #[cfg(feature = "image")] 406 | fn test_jelly_beans_image() { 407 | let img = image::open("data/octocat.png").unwrap(); 408 | 409 | let blurhash = encode_image(4, 3, &img.to_rgba8()).unwrap(); 410 | 411 | assert_eq!(blurhash, "LNAdAqj[00aymkj[TKay9}ay-Sj["); 412 | } 413 | 414 | #[test] 415 | #[cfg(feature = "image")] 416 | fn decode_blurhash_image() { 417 | let img = image::open("data/octocat.png").unwrap(); 418 | let (width, height) = img.dimensions(); 419 | 420 | let blurhash = encode_image(4, 3, &img.to_rgba8()).unwrap(); 421 | let img = decode_image(&blurhash, width, height, 1.0).unwrap(); 422 | 423 | assert_eq!(img.as_bytes()[0..5], [1, 1, 1, 255, 1]); 424 | } 425 | 426 | #[test] 427 | #[cfg(feature = "gdk-pixbuf")] 428 | fn test_jelly_beans_pixbuf() { 429 | let img = gdk_pixbuf::Pixbuf::from_file("data/octocat.png").unwrap(); 430 | 431 | let blurhash = encode_pixbuf(4, 3, &img).unwrap(); 432 | 433 | assert_eq!(blurhash, "LNAdAqj[00aymkj[TKay9}ay-Sj["); 434 | } 435 | 436 | #[test] 437 | #[cfg(feature = "gdk-pixbuf")] 438 | fn decode_blurhash_pixbuf() { 439 | use std::convert::TryInto; 440 | let img = gdk_pixbuf::Pixbuf::from_file("data/wikipedia_logo.png").unwrap(); 441 | 442 | let blurhash = encode_pixbuf(4, 3, &img).unwrap(); 443 | let img = decode_pixbuf( 444 | &blurhash, 445 | img.width().try_into().unwrap(), 446 | img.height().try_into().unwrap(), 447 | 1.0, 448 | ) 449 | .unwrap(); 450 | 451 | let target = image::open("data/wikipedia_logo_blurred.png").unwrap(); 452 | assert_image_data_approximately_equal(&img.read_pixel_bytes(), target.as_bytes()) 453 | } 454 | 455 | #[cfg(feature = "gdk-pixbuf")] 456 | fn assert_image_data_approximately_equal(result: &[u8], target: &[u8]) { 457 | const MAX_AVERAGE_ERROR: usize = 1; 458 | const MAX_PEAK_ERROR: usize = 8; 459 | 460 | assert_eq!( 461 | result.len(), 462 | target.len(), 463 | "images do not have the same shape: {} vs {}", 464 | result.len(), 465 | target.len() 466 | ); 467 | 468 | let mut aggregated_error: usize = 0; 469 | let mut peak_error = 0; 470 | for (r, t) in result.iter().zip(target) { 471 | let error = (*r as isize - *t as isize).abs() as usize; 472 | aggregated_error += error; 473 | peak_error = peak_error.max(error); 474 | } 475 | 476 | let average_error = aggregated_error / result.len(); 477 | 478 | assert!( 479 | average_error <= MAX_AVERAGE_ERROR, 480 | "images do not look similar. average error {} > {}", 481 | average_error, 482 | MAX_AVERAGE_ERROR 483 | ); 484 | assert!( 485 | peak_error <= MAX_PEAK_ERROR, 486 | "images do not look similar. peak error {} > {}", 487 | peak_error, 488 | MAX_PEAK_ERROR, 489 | ); 490 | } 491 | 492 | fn base83_string(len: usize) -> impl Strategy { 493 | let reg = format!("([A-Za-z0-9#$%*+,-.:;=?@\\[\\]^_{{|}}~]){{{len}}}"); 494 | proptest::string::string_regex(®).unwrap() 495 | } 496 | 497 | prop_compose! { 498 | fn valid_blurhash() 499 | (num_x in 1..10u32, num_y in 1..10u32) 500 | (blurhash in base83_string(3 + 2 * num_x as usize * num_y as usize), num_x in Just(num_x), num_y in Just(num_y)) 501 | -> String { 502 | let mut blurhash_with_size = String::with_capacity(4 + 2 * num_x as usize * num_y as usize); 503 | let size_flag = (num_x - 1) + (num_y - 1) * 9; 504 | base83::encode_into(size_flag, 1, &mut blurhash_with_size); 505 | blurhash_with_size.push_str(&blurhash); 506 | blurhash_with_size 507 | } 508 | } 509 | 510 | proptest! { 511 | #[test] 512 | fn roundtrip_octocat(x_components in 1..10u32, y_components in 1..10u32, punch in 0.0..1.0f32) { 513 | let img = image::open("data/octocat.png").unwrap(); 514 | let (width, height) = img.dimensions(); 515 | 516 | let blurhash = encode(x_components, y_components, width, height, img.to_rgba8().as_bytes()).unwrap(); 517 | let _img = decode(&blurhash, width, height, punch).unwrap(); 518 | } 519 | 520 | #[test] 521 | fn decode_doesnt_panic( 522 | blurhash in "([A-Za-z0-9+/]{4}){2,}", 523 | width in 1..1000u32, 524 | height in 1..1000u32, 525 | punch in 0.0..1.0f32, 526 | ) { 527 | let _ = decode(&blurhash, width, height, punch); 528 | } 529 | 530 | #[test] 531 | fn decode_valid_blurhash( 532 | width in 10..100u32, 533 | height in 10..100u32, 534 | blurhash in valid_blurhash(), 535 | ) { 536 | 537 | let img = decode(&blurhash, width, height, 1.); 538 | proptest::prop_assert!(img.is_ok(), "{}", img.unwrap_err()); 539 | } 540 | } 541 | } 542 | -------------------------------------------------------------------------------- /src/util.rs: -------------------------------------------------------------------------------- 1 | include!(concat!(env!("OUT_DIR"), "/srgb_lookup.rs")); 2 | 3 | /// linear 0.0-1.0 floating point to srgb 0-255 integer conversion. 4 | #[cfg(not(feature = "fast-linear-to-srgb"))] 5 | pub fn linear_to_srgb(value: f32) -> u8 { 6 | let v = value.clamp(0., 1.); 7 | if v <= 0.003_130_8 { 8 | (v * 12.92 * 255. + 0.5).round() as u8 9 | } else { 10 | // The original C implementation uses this formula: 11 | // ((1.055 * f32::powf(v, 1. / 2.4) - 0.055) * 255. + 0.5).round() as u8 12 | // But we can distribute the latter multiplication, to reduce the number of operations: 13 | ((1.055 * 255.) * f32::powf(v, 1. / 2.4) - (0.055 * 255. - 0.5)).round() as u8 14 | } 15 | } 16 | 17 | /// linear 0.0-1.0 floating point to srgb 0-255 integer conversion. 18 | #[cfg(feature = "fast-linear-to-srgb")] 19 | pub fn linear_to_srgb(value: f32) -> u8 { 20 | let v = value.clamp(0.0, 1.0); 21 | let index = 22 | ((LINEAR_TO_SRGB_LOOKUP_SIZE as f32 * v) as usize).min(LINEAR_TO_SRGB_LOOKUP_SIZE - 1); 23 | LINEAR_TO_SRGB_LOOKUP[index] 24 | } 25 | 26 | /// srgb 0-255 integer to linear 0.0-1.0 floating point conversion. 27 | pub fn srgb_to_linear(value: u8) -> f32 { 28 | SRGB_LOOKUP[value as usize] 29 | } 30 | 31 | pub fn sign_pow(val: f32, exp: f32) -> f32 { 32 | f32::copysign(f32::powf(val.abs(), exp), val) 33 | } 34 | --------------------------------------------------------------------------------