├── test ├── test_helper.exs ├── support │ ├── images │ │ ├── elixir-logo.png │ │ ├── elixir-logo.qoi │ │ └── elixir-logo.raw │ └── generators.ex ├── qoix │ └── image_test.exs └── qoix_test.exs ├── .formatter.exs ├── .github └── workflows │ └── ci.yaml ├── .gitignore ├── mix.exs ├── README.md ├── mix.lock ├── lib ├── qoix │ └── image.ex └── qoix.ex └── LICENSE /test/test_helper.exs: -------------------------------------------------------------------------------- 1 | ExUnit.start() 2 | -------------------------------------------------------------------------------- /test/support/images/elixir-logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rbino/qoix/HEAD/test/support/images/elixir-logo.png -------------------------------------------------------------------------------- /test/support/images/elixir-logo.qoi: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rbino/qoix/HEAD/test/support/images/elixir-logo.qoi -------------------------------------------------------------------------------- /test/support/images/elixir-logo.raw: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rbino/qoix/HEAD/test/support/images/elixir-logo.raw -------------------------------------------------------------------------------- /.formatter.exs: -------------------------------------------------------------------------------- 1 | # Used by "mix format" 2 | [ 3 | import_deps: [:stream_data], 4 | inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"] 5 | ] 6 | -------------------------------------------------------------------------------- /.github/workflows/ci.yaml: -------------------------------------------------------------------------------- 1 | on: 2 | push: 3 | create: 4 | pull_request: 5 | 6 | jobs: 7 | test: 8 | runs-on: ubuntu-latest 9 | name: OTP ${{matrix.otp}} / Elixir ${{matrix.elixir}} 10 | strategy: 11 | matrix: 12 | otp: ['23.3', '24.1'] 13 | elixir: ['1.12.3'] 14 | steps: 15 | - uses: actions/checkout@v2 16 | - uses: erlef/setup-beam@v1 17 | with: 18 | otp-version: ${{matrix.otp}} 19 | elixir-version: ${{matrix.elixir}} 20 | - run: mix deps.get 21 | - run: mix test 22 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # The directory Mix will write compiled artifacts to. 2 | /_build/ 3 | 4 | # If you run "mix test --cover", coverage assets end up here. 5 | /cover/ 6 | 7 | # The directory Mix downloads your dependencies sources to. 8 | /deps/ 9 | 10 | # Where third-party dependencies like ExDoc output generated docs. 11 | /doc/ 12 | 13 | # Ignore .fetch files in case you like to edit your project deps locally. 14 | /.fetch 15 | 16 | # If the VM crashes, it generates a dump, let's ignore it too. 17 | erl_crash.dump 18 | 19 | # Also ignore archive artifacts (built via "mix archive.build"). 20 | *.ez 21 | 22 | # Ignore package tarball (built via "mix hex.build"). 23 | qoix-*.tar 24 | 25 | # Temporary files, for example, from tests. 26 | /tmp/ 27 | -------------------------------------------------------------------------------- /test/qoix/image_test.exs: -------------------------------------------------------------------------------- 1 | defmodule Qoix.ImageTest do 2 | use ExUnit.Case 3 | use ExUnitProperties 4 | doctest Qoix 5 | 6 | import Qoix.Generators 7 | alias Qoix.Image 8 | 9 | describe "from_rgb/3" do 10 | property "simply wraps the passed arguments, adding the correct format" do 11 | check all {width, height, rgb_pixels} <- rgb_image_data_generator() do 12 | assert %Image{width: ^width, height: ^height, pixels: ^rgb_pixels, format: :rgb} = 13 | Image.from_rgb(width, height, rgb_pixels) 14 | end 15 | end 16 | end 17 | 18 | describe "from_rgba/3" do 19 | property "simply wraps the passed arguments, adding the correct format" do 20 | check all {width, height, pixels} <- rgb_image_data_generator() do 21 | assert %Image{width: ^width, height: ^height, pixels: ^pixels, format: :rgba} = 22 | Image.from_rgba(width, height, pixels) 23 | end 24 | end 25 | end 26 | end 27 | -------------------------------------------------------------------------------- /test/support/generators.ex: -------------------------------------------------------------------------------- 1 | defmodule Qoix.Generators do 2 | use ExUnitProperties 3 | 4 | def rgb_image_data_generator do 5 | gen all width <- positive_integer(), 6 | height <- positive_integer() do 7 | pixels = 8 | rgb_pixel_generator() 9 | |> Enum.take(width * height) 10 | |> IO.iodata_to_binary() 11 | 12 | {width, height, pixels} 13 | end 14 | end 15 | 16 | def rgb_pixel_generator do 17 | gen all r <- byte_generator(), 18 | g <- byte_generator(), 19 | b <- byte_generator() do 20 | <> 21 | end 22 | end 23 | 24 | def rgba_image_data_generator do 25 | gen all width <- positive_integer(), 26 | height <- positive_integer() do 27 | pixels = 28 | rgba_pixel_generator() 29 | |> Enum.take(width * height) 30 | |> IO.iodata_to_binary() 31 | 32 | {width, height, pixels} 33 | end 34 | end 35 | 36 | def rgba_pixel_generator do 37 | gen all r <- byte_generator(), 38 | g <- byte_generator(), 39 | b <- byte_generator(), 40 | a <- byte_generator() do 41 | <> 42 | end 43 | end 44 | 45 | def byte_generator do 46 | map(positive_integer(), &rem(&1, 256)) 47 | end 48 | end 49 | -------------------------------------------------------------------------------- /mix.exs: -------------------------------------------------------------------------------- 1 | defmodule Qoix.MixProject do 2 | use Mix.Project 3 | 4 | @source_url "https://github.com/rbino/qoix" 5 | @version "0.1.0" 6 | 7 | def project do 8 | [ 9 | app: :qoix, 10 | name: "Qoix", 11 | version: @version, 12 | elixir: "~> 1.12", 13 | elixirc_paths: elixirc_paths(Mix.env()), 14 | start_permanent: Mix.env() == :prod, 15 | package: package(), 16 | deps: deps(), 17 | docs: docs() 18 | ] 19 | end 20 | 21 | # Run "mix help compile.app" to learn about applications. 22 | def application do 23 | [ 24 | extra_applications: [:logger] 25 | ] 26 | end 27 | 28 | # Specifies which paths to compile per environment. 29 | defp elixirc_paths(:test), do: ["lib", "test/support"] 30 | defp elixirc_paths(_), do: ["lib"] 31 | 32 | # Run "mix help deps" to learn about dependencies. 33 | defp deps do 34 | [ 35 | {:stream_data, "~> 0.5", only: [:dev, :test]}, 36 | {:ex_doc, ">= 0.0.0", only: :dev, runtime: false} 37 | ] 38 | end 39 | 40 | defp package do 41 | [ 42 | description: "Qoix is an Elixir implementation of the Quite OK Image format.", 43 | licenses: ["Apache-2.0"], 44 | links: %{"GitHub" => @source_url} 45 | ] 46 | end 47 | 48 | defp docs do 49 | [ 50 | extras: [ 51 | LICENSE: [title: "License"], 52 | "README.md": [title: "Overview"] 53 | ], 54 | main: "readme", 55 | source_url: @source_url, 56 | formatters: ["html"] 57 | ] 58 | end 59 | end 60 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Qoix 2 | 3 | [![Build Status](https://github.com/rbino/qoix/actions/workflows/ci.yaml/badge.svg)](https://github.com/rbino/qoix/actions/workflows/ci.yaml) 4 | [![Hex Version](https://img.shields.io/hexpm/v/qoix.svg)](https://hex.pm/packages/qoix) 5 | [![Hex Docs](https://img.shields.io/badge/hex-docs-lightgreen.svg)](https://hexdocs.pm/qoix/) 6 | [![Total Download](https://img.shields.io/hexpm/dt/qoix.svg)](https://hex.pm/packages/qoix) 7 | [![License](https://img.shields.io/hexpm/l/qoix.svg)](https://github.com/rbino/qoix/blob/master/LICENSE) 8 | [![Last Updated](https://img.shields.io/github/last-commit/rbino/qoix.svg)](https://github.com/rbino/qoix/commits/master) 9 | 10 | 11 | Qoix is an Elixir implementation of the [Quite OK Image format](https://qoiformat.org). 12 | 13 | It is currently aligned with the [v1.0 specification](https://qoiformat.org/qoi-specification.pdf). 14 | 15 | ## Installation 16 | 17 | The package can be installed by adding `:qoix` to your list of dependencies in `mix.exs`: 18 | 19 | ```elixir 20 | def deps do 21 | [ 22 | {:qoix, "~> 0.1.0"} 23 | ] 24 | end 25 | ``` 26 | 27 | ## Copyright and License 28 | 29 | Copyright (c) 2021 Riccardo Binetti 30 | 31 | Licensed under the Apache License, Version 2.0 (the "License"); 32 | you may not use this file except in compliance with the License. 33 | You may obtain a copy of the License at [https://www.apache.org/licenses/LICENSE-2.0](https://www.apache.org/licenses/LICENSE-2.0) 34 | 35 | Unless required by applicable law or agreed to in writing, software 36 | distributed under the License is distributed on an "AS IS" BASIS, 37 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 38 | See the License for the specific language governing permissions and 39 | limitations under the License. 40 | -------------------------------------------------------------------------------- /mix.lock: -------------------------------------------------------------------------------- 1 | %{ 2 | "earmark_parser": {:hex, :earmark_parser, "1.4.18", "e1b2be73eb08a49fb032a0208bf647380682374a725dfb5b9e510def8397f6f2", [:mix], [], "hexpm", "114a0e85ec3cf9e04b811009e73c206394ffecfcc313e0b346de0d557774ee97"}, 3 | "ex_doc": {:hex, :ex_doc, "0.26.0", "1922164bac0b18b02f84d6f69cab1b93bc3e870e2ad18d5dacb50a9e06b542a3", [:mix], [{:earmark_parser, "~> 1.4.0", [hex: :earmark_parser, repo: "hexpm", optional: false]}, {:makeup_elixir, "~> 0.14", [hex: :makeup_elixir, repo: "hexpm", optional: false]}, {:makeup_erlang, "~> 0.1", [hex: :makeup_erlang, repo: "hexpm", optional: false]}], "hexpm", "2775d66e494a9a48355db7867478ffd997864c61c65a47d31c4949459281c78d"}, 4 | "makeup": {:hex, :makeup, "1.0.5", "d5a830bc42c9800ce07dd97fa94669dfb93d3bf5fcf6ea7a0c67b2e0e4a7f26c", [:mix], [{:nimble_parsec, "~> 0.5 or ~> 1.0", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "cfa158c02d3f5c0c665d0af11512fed3fba0144cf1aadee0f2ce17747fba2ca9"}, 5 | "makeup_elixir": {:hex, :makeup_elixir, "0.15.2", "dc72dfe17eb240552857465cc00cce390960d9a0c055c4ccd38b70629227e97c", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}, {:nimble_parsec, "~> 1.1", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "fd23ae48d09b32eff49d4ced2b43c9f086d402ee4fd4fcb2d7fad97fa8823e75"}, 6 | "makeup_erlang": {:hex, :makeup_erlang, "0.1.1", "3fcb7f09eb9d98dc4d208f49cc955a34218fc41ff6b84df7c75b3e6e533cc65f", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}], "hexpm", "174d0809e98a4ef0b3309256cbf97101c6ec01c4ab0b23e926a9e17df2077cbb"}, 7 | "nimble_parsec": {:hex, :nimble_parsec, "1.2.0", "b44d75e2a6542dcb6acf5d71c32c74ca88960421b6874777f79153bbbbd7dccc", [:mix], [], "hexpm", "52b2871a7515a5ac49b00f214e4165a40724cf99798d8e4a65e4fd64ebd002c1"}, 8 | "stream_data": {:hex, :stream_data, "0.5.0", "b27641e58941685c75b353577dc602c9d2c12292dd84babf506c2033cd97893e", [:mix], [], "hexpm", "012bd2eec069ada4db3411f9115ccafa38540a3c78c4c0349f151fc761b9e271"}, 9 | } 10 | -------------------------------------------------------------------------------- /lib/qoix/image.ex: -------------------------------------------------------------------------------- 1 | defmodule Qoix.Image do 2 | @moduledoc """ 3 | A struct representing a raw image. 4 | """ 5 | 6 | @enforce_keys [:width, :height, :pixels, :format, :colorspace] 7 | defstruct [:width, :height, :pixels, :format, :colorspace] 8 | 9 | @type colorspace :: :srgb | :linear 10 | @type format :: :rgb | :rgba 11 | @type t :: %__MODULE__{ 12 | width: pos_integer, 13 | height: pos_integer, 14 | pixels: binary, 15 | format: format, 16 | colorspace: colorspace 17 | } 18 | 19 | alias __MODULE__ 20 | 21 | @doc """ 22 | Creates a new `Qoix.Image` with :rgb format. 23 | 24 | `pixels` must be a binary of RGB values. 25 | 26 | It's possible to pass an optional `colorspace`, which must be one of `:srgb` (sRGB with linear 27 | alpha) or `:linear` (all channels linear). If nothing is passed, the default is `:srgb` 28 | """ 29 | @spec from_rgb(pos_integer, pos_integer, binary, colorspace) :: t 30 | def from_rgb(width, height, pixels, colorspace \\ :srgb) 31 | when is_integer(width) and is_integer(height) and is_binary(pixels) and width > 0 and 32 | height > 0 and colorspace in [:srgb, :linear] do 33 | %Image{ 34 | width: width, 35 | height: height, 36 | pixels: pixels, 37 | format: :rgb, 38 | colorspace: colorspace 39 | } 40 | end 41 | 42 | @doc """ 43 | Creates a new `Qoix.Image` with :rgba format. 44 | 45 | `pixels` must be a binary of RGBA values. 46 | 47 | It's possible to pass an optional `colorspace`, which must be one of `:srgb` (sRGB with linear 48 | alpha) or `:linear` (all channels linear). If nothing is passed, the default is `:srgb` 49 | """ 50 | @spec from_rgba(pos_integer, pos_integer, binary, colorspace) :: t 51 | def from_rgba(width, height, pixels, colorspace \\ :srgb) 52 | when is_integer(width) and is_integer(height) and is_binary(pixels) and width > 0 and 53 | height > 0 and colorspace in [:srgb, :linear] do 54 | %Image{ 55 | width: width, 56 | height: height, 57 | pixels: pixels, 58 | format: :rgba, 59 | colorspace: colorspace 60 | } 61 | end 62 | end 63 | -------------------------------------------------------------------------------- /test/qoix_test.exs: -------------------------------------------------------------------------------- 1 | defmodule QoixTest do 2 | use ExUnit.Case 3 | use ExUnitProperties 4 | doctest Qoix 5 | 6 | import Qoix.Generators 7 | alias Qoix.Image 8 | 9 | @raw_logo_path "test/support/images/elixir-logo.raw" 10 | @qoi_logo_path "test/support/images/elixir-logo.qoi" 11 | @logo_width 554 12 | @logo_height 690 13 | 14 | describe "encode/1" do 15 | property "the resulting image has the correct header dimensions and padding" do 16 | check all {width, height, rgba_pixels} <- rgba_image_data_generator() do 17 | assert {:ok, encoded} = 18 | Image.from_rgba(width, height, rgba_pixels) 19 | |> Qoix.encode() 20 | 21 | assert <<"qoif", ^width::32, ^height::32, channels::8, _colorspace::8, data::binary>> = 22 | encoded 23 | 24 | assert channels == 4 25 | padding_start = byte_size(data) - 8 26 | assert :binary.part(data, padding_start, 8) == <<0, 0, 0, 0, 0, 0, 0, 1>> 27 | assert byte_size(data) <= rgba_pixels 28 | 29 | assert Qoix.qoi?(encoded) == true 30 | end 31 | end 32 | 33 | test "correctly encodes the Elixir logo" do 34 | raw_image = 35 | @raw_logo_path 36 | |> File.read!() 37 | |> then(&Image.from_rgba(@logo_width, @logo_height, &1)) 38 | 39 | qoi_logo = File.read!(@qoi_logo_path) 40 | 41 | assert {:ok, encoded} = Qoix.encode(raw_image) 42 | assert encoded == qoi_logo 43 | end 44 | end 45 | 46 | describe "decode/1" do 47 | property "round trips with rgba images" do 48 | check all {width, height, rgba_pixels} <- rgba_image_data_generator() do 49 | image = Image.from_rgba(width, height, rgba_pixels) 50 | 51 | {:ok, encoded} = Qoix.encode(image) 52 | 53 | assert {:ok, ^image} = Qoix.decode(encoded) 54 | end 55 | end 56 | 57 | property "round trips with rgb images" do 58 | check all {width, height, rgb_pixels} <- rgb_image_data_generator() do 59 | image = Image.from_rgb(width, height, rgb_pixels) 60 | 61 | {:ok, encoded} = Qoix.encode(image) 62 | 63 | assert {:ok, ^image} = Qoix.decode(encoded) 64 | end 65 | end 66 | 67 | test "correctly decodes the Elixir logo" do 68 | qoi_logo = File.read!(@qoi_logo_path) 69 | 70 | raw_image = 71 | @raw_logo_path 72 | |> File.read!() 73 | |> then(&Image.from_rgba(@logo_width, @logo_height, &1)) 74 | 75 | assert {:ok, decoded} = Qoix.decode(qoi_logo) 76 | assert decoded == raw_image 77 | end 78 | end 79 | end 80 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /lib/qoix.ex: -------------------------------------------------------------------------------- 1 | defmodule Qoix do 2 | @moduledoc """ 3 | Qoix is an Elixir implementation of the [Quite OK Image format](https://qoiformat.org). 4 | """ 5 | 6 | alias Qoix.Image 7 | use Bitwise 8 | 9 | @index_op <<0::2>> 10 | @diff_op <<1::2>> 11 | @luma_op <<2::2>> 12 | @run_op <<3::2>> 13 | @rgb_op <<254::8>> 14 | @rgba_op <<255::8>> 15 | @padding :binary.copy(<<0>>, 7) <> <<1>> 16 | @empty_lut for i <- 0..63, into: %{}, do: {i, <<0::32>>} 17 | 18 | @doc """ 19 | Returns true if the binary appears to contain a valid QOI image. 20 | """ 21 | @spec qoi?(binary) :: boolean 22 | def qoi?(<<"qoif", _width::32, _height::32, channels::8, cspace::8, _rest::binary>> = _binary) 23 | when channels in [3, 4] and cspace in [0, 1] do 24 | true 25 | end 26 | 27 | def qoi?(binary) when is_binary(binary) do 28 | false 29 | end 30 | 31 | @doc """ 32 | Encodes a `%Qoix.Image{}` using QOI, returning a binary with the encoded image. 33 | 34 | Returns `{:ok, encoded}` on success, `{:error, reason}` on failure. 35 | """ 36 | @spec encode(Qoix.Image.t()) :: {:ok, binary} | {:error, any} 37 | def encode(%Image{width: w, height: h, pixels: pixels, format: fmt, colorspace: cspace}) 38 | when w > 0 and h > 0 and fmt in [:rgb, :rgba] and cspace in [:srgb, :linear] and 39 | is_binary(pixels) do 40 | channels = channels(fmt) 41 | colorspace = encode_colorspace(cspace) 42 | 43 | chunks = 44 | pixels 45 | |> encode_pixels(fmt) 46 | |> IO.iodata_to_binary() 47 | 48 | # Return the final binary 49 | data = <<"qoif", w::32, h::32, channels::8, colorspace::8, chunks::bits, @padding::bits>> 50 | 51 | {:ok, data} 52 | end 53 | 54 | defp channels(:rgb), do: 3 55 | defp channels(:rgba), do: 4 56 | 57 | defp encode_colorspace(:srgb), do: 0 58 | defp encode_colorspace(:linear), do: 1 59 | 60 | defp encode_pixels(<>, format) when format == :rgb or format == :rgba do 61 | # Previous pixel is initialized to 0,0,0,255 62 | prev = <<0, 0, 0, 255>> 63 | run_length = 0 64 | lut = @empty_lut 65 | acc = [] 66 | 67 | do_encode(pixels, format, prev, run_length, lut, acc) 68 | end 69 | 70 | # Here we go with all the possible cases. Order matters due to pattern matching. 71 | 72 | # Maximum representable run_length, push out and start a new one 73 | defp do_encode(<>, format, prev, run_length, lut, acc) when run_length == 62 do 74 | acc = [acc | <<@run_op::bits, bias_run(run_length)::6>>] 75 | 76 | do_encode(pixels, format, prev, 0, lut, acc) 77 | end 78 | 79 | # Same RGBA pixel as previous, consume and increase run_length 80 | defp do_encode(<>, :rgba = format, <>, run_length, lut, acc) do 81 | do_encode(rest, format, <>, run_length + 1, lut, acc) 82 | end 83 | 84 | # Same RGB pixel as previous, consume and increase run_length 85 | defp do_encode(<>, :rgb = format, <>, run_length, lut, acc) do 86 | do_encode(rest, format, <>, run_length + 1, lut, acc) 87 | end 88 | 89 | # Since we didn't match the previous head, the pixel is different from the previous. 90 | # We don't have any ongoing run_length, so we just have to handle the pixel. 91 | defp do_encode(<>, :rgba = format, prev, 0, lut, acc) do 92 | pixel = <> 93 | 94 | {chunk, new_lut} = handle_non_running_pixel(pixel, prev, lut) 95 | acc = [acc | chunk] 96 | 97 | do_encode(rest, format, pixel, 0, new_lut, acc) 98 | end 99 | 100 | # As above, but for RGB 101 | defp do_encode(<>, :rgb = format, prev, 0, lut, acc) do 102 | pixel = <> 103 | 104 | {chunk, new_lut} = handle_non_running_pixel(pixel, prev, lut) 105 | acc = [acc | chunk] 106 | 107 | do_encode(rest, format, pixel, 0, new_lut, acc) 108 | end 109 | 110 | # For the same reason as above, the pixel is different from the previous. 111 | # Here we just emit the run length and leave the pixel handling to the next recursion, 112 | # that will enter in the previous head. 113 | defp do_encode(<>, format, prev, run_length, lut, acc) 114 | when run_length > 0 do 115 | acc = [acc | <<@run_op::bits, bias_run(run_length)::6>>] 116 | 117 | do_encode(pixels, format, prev, 0, lut, acc) 118 | end 119 | 120 | # All pixels consumed, no ongoing run: just output the accumulator 121 | defp do_encode(<<>>, _format, _prev, 0, _lut, acc) do 122 | acc 123 | end 124 | 125 | # All pixels consumed, pending run: output the accumulator and the 6 bit run with its tag 126 | defp do_encode(<<>>, _format, _prev, run_length, _lut, acc) do 127 | [acc | <<@run_op::bits, bias_run(run_length)::6>>] 128 | end 129 | 130 | # Handle a pixel that is not part of a run, return a {chunk, updated_lut} tuple 131 | defp handle_non_running_pixel(<> = pixel, prev, lut) do 132 | index = index(r, g, b, a) 133 | 134 | case lut do 135 | %{^index => <<^r::8, ^g::8, ^b::8, ^a::8>>} -> 136 | {<<@index_op::bits, index::6>>, lut} 137 | 138 | _other -> 139 | # The value was different from our current pixel 140 | chunk = diff_luma_color(pixel, prev) 141 | new_lut = Map.put(lut, index, <>) 142 | 143 | {chunk, new_lut} 144 | end 145 | end 146 | 147 | defguardp in_range_2?(val) when val in -2..1 148 | defguardp in_range_4?(val) when val in -8..7 149 | defguardp in_range_6?(val) when val in -32..31 150 | 151 | # Check if value can be represented with diff op 152 | defguardp diff_op?(dr, dg, db) when in_range_2?(dr) and in_range_2?(dg) and in_range_2?(db) 153 | 154 | # Check if value can be represented with luma op 155 | defguardp luma_op?(dr, dg, db) 156 | when in_range_6?(dg) and in_range_4?(dr - dg) and in_range_4?(db - dg) 157 | 158 | # Emit a diff, luma, rgb or rgba chunk 159 | defp diff_luma_color(<> = _pixel, <> = _prev) 160 | when diff_op?(r - pr, g - pg, b - pb) do 161 | <<@diff_op::bits, bias_diff(r - pr)::2, bias_diff(g - pg)::2, bias_diff(b - pb)::2>> 162 | end 163 | 164 | defp diff_luma_color(<> = _pixel, <> = _prev) 165 | when luma_op?(r - pr, g - pg, b - pb) do 166 | dg = g - pg 167 | dr_dg = r - pr - dg 168 | db_dg = b - pb - dg 169 | 170 | <<@luma_op::bits, bias_luma_dg(dg)::6, bias_luma_dr_db(dr_dg)::4, bias_luma_dr_db(db_dg)::4>> 171 | end 172 | 173 | defp diff_luma_color(<>, <<_prgb::24, a::8>> = _prev) do 174 | # Same alpha, emit RGB 175 | <<@rgb_op, r::8, g::8, b::8>> 176 | end 177 | 178 | defp diff_luma_color(<>, _prev) do 179 | # Last resort, full RGBA color 180 | <<@rgba_op, r::8, g::8, b::8, a::8>> 181 | end 182 | 183 | @doc """ 184 | Decodes a QOI image, returning an `%Image{}`. 185 | 186 | Returns `{:ok, %Image{}}` on success, `{:error, reason}` on failure. 187 | """ 188 | @spec decode(binary) :: {:ok, Qoix.Image.t()} | {:error, any} 189 | def decode(<> = _encoded) do 190 | case encoded do 191 | <<"qoif", width::32, height::32, channels::8, cspace::8, chunks::binary>> -> 192 | format = format(channels) 193 | colorspace = decode_colorspace(cspace) 194 | 195 | pixels = 196 | chunks 197 | |> decode_chunks(format) 198 | |> IO.iodata_to_binary() 199 | 200 | image = %Image{ 201 | width: width, 202 | height: height, 203 | pixels: pixels, 204 | format: format, 205 | colorspace: colorspace 206 | } 207 | 208 | {:ok, image} 209 | 210 | _ -> 211 | {:error, :invalid_qoi} 212 | end 213 | end 214 | 215 | defp format(3), do: :rgb 216 | defp format(4), do: :rgba 217 | 218 | defp decode_colorspace(0), do: :srgb 219 | defp decode_colorspace(1), do: :linear 220 | 221 | defp decode_chunks(<>, format) do 222 | # Previous pixel is initialized to 0,0,0,255 223 | prev = <<0, 0, 0, 255>> 224 | lut = @empty_lut 225 | acc = [] 226 | 227 | do_decode(chunks, format, prev, lut, acc) 228 | end 229 | 230 | # Let's decode, order matters since 8 bit opcodes have predence over 2 bit opcodes 231 | 232 | # Final padding, we're done, return the accumulator 233 | defp do_decode(@padding, _format, _prev, _lut, acc) do 234 | acc 235 | end 236 | 237 | # RGB: take just alpha from previous pixel 238 | defp do_decode(<<@rgb_op, r::8, g::8, b::8, rest::bits>>, format, prev, lut, acc) do 239 | <<_prgb::24, pa::8>> = prev 240 | 241 | pixel = <> 242 | acc = [acc | maybe_drop_alpha(pixel, format)] 243 | 244 | do_decode(rest, format, pixel, update_lut(lut, pixel), acc) 245 | end 246 | 247 | # RGBA: pixel encoded with full information 248 | defp do_decode(<<@rgba_op, r::8, g::8, b::8, a::8, rest::bits>>, format, _prev, lut, acc) do 249 | pixel = <> 250 | acc = [acc | maybe_drop_alpha(pixel, format)] 251 | 252 | do_decode(rest, format, pixel, update_lut(lut, pixel), acc) 253 | end 254 | 255 | # Index: get the pixel from the LUT 256 | defp do_decode(<<@index_op, index::6, rest::bits>>, format, _prev, lut, acc) do 257 | %{^index => pixel} = lut 258 | acc = [acc | maybe_drop_alpha(pixel, format)] 259 | 260 | do_decode(rest, format, pixel, lut, acc) 261 | end 262 | 263 | # Run: repeat previous pixel 264 | defp do_decode(<<@run_op, count::6, rest::bits>>, format, prev, lut, acc) do 265 | pixels = 266 | maybe_drop_alpha(prev, format) 267 | |> :binary.copy(unbias_run(count)) 268 | 269 | acc = [acc | pixels] 270 | 271 | do_decode(rest, format, prev, lut, acc) 272 | end 273 | 274 | # Diff: reconstruct pixel from previous + diff 275 | defp do_decode(<<@diff_op, dr::2, dg::2, db::2, rest::bits>>, format, prev, lut, acc) do 276 | <> = prev 277 | r = pr + unbias_diff(dr) 278 | g = pg + unbias_diff(dg) 279 | b = pb + unbias_diff(db) 280 | 281 | pixel = <> 282 | acc = [acc | maybe_drop_alpha(pixel, format)] 283 | 284 | do_decode(rest, format, pixel, update_lut(lut, pixel), acc) 285 | end 286 | 287 | # Luma: reconstruct pixel from previous + diff 288 | defp do_decode(<<@luma_op, b_dg::6, dr_dg::4, db_dg::4, rest::bits>>, format, prev, lut, acc) do 289 | <> = prev 290 | dg = unbias_luma_dg(b_dg) 291 | r = pr + unbias_luma_dr_db(dr_dg) + dg 292 | g = pg + dg 293 | b = pb + unbias_luma_dr_db(db_dg) + dg 294 | 295 | pixel = <> 296 | acc = [acc | maybe_drop_alpha(pixel, format)] 297 | 298 | do_decode(rest, format, pixel, update_lut(lut, pixel), acc) 299 | end 300 | 301 | defp maybe_drop_alpha(pixel, :rgba), do: pixel 302 | defp maybe_drop_alpha(<>, :rgb), do: <> 303 | 304 | defp index(r, g, b, a) do 305 | (r * 3 + g * 5 + b * 7 + a * 11) 306 | |> rem(64) 307 | end 308 | 309 | defp update_lut(lut, <>) do 310 | lut_index = index(r, g, b, a) 311 | 312 | Map.put(lut, lut_index, <>) 313 | end 314 | 315 | defp bias_run(val), do: val - 1 316 | defp unbias_run(val), do: val + 1 317 | 318 | defp bias_diff(val), do: val + 2 319 | defp unbias_diff(val), do: val - 2 320 | 321 | defp bias_luma_dg(val), do: val + 32 322 | defp unbias_luma_dg(val), do: val - 32 323 | 324 | defp bias_luma_dr_db(val), do: val + 8 325 | defp unbias_luma_dr_db(val), do: val - 8 326 | end 327 | --------------------------------------------------------------------------------