Skip to main content

jixel_image_bindings/
lib.rs

1/*
2 * // Copyright (c) Radzivon Bartoshyk 8/2026. All rights reserved.
3 * //
4 * // Redistribution and use in source and binary forms, with or without modification,
5 * // are permitted provided that the following conditions are met:
6 * //
7 * // 1.  Redistributions of source code must retain the above copyright notice, this
8 * // list of conditions and the following disclaimer.
9 * //
10 * // 2.  Redistributions in binary form must reproduce the above copyright notice,
11 * // this list of conditions and the following disclaimer in the documentation
12 * // and/or other materials provided with the distribution.
13 * //
14 * // 3.  Neither the name of the copyright holder nor the names of its
15 * // contributors may be used to endorse or promote products derived from
16 * // this software without specific prior written permission.
17 * //
18 * // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19 * // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 * // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21 * // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
22 * // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23 * // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
24 * // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25 * // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
26 * // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 * // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 */
29
30#![forbid(unsafe_code)]
31
32mod alpha;
33
34use std::io::Write;
35
36use alpha::has_alpha;
37use image::error::{
38    EncodingError, ImageFormatHint, ParameterError, ParameterErrorKind, UnsupportedError,
39    UnsupportedErrorKind,
40};
41use image::{DynamicImage, ExtendedColorType, ImageEncoder, ImageError, ImageResult};
42
43pub use jixel::{
44    ColorEncoding, ColorSpace, EncodeConfig, Orientation, Primaries, RenderingIntent, Speed,
45    TransferFunction, WhitePoint, distance_from_quality,
46};
47
48pub struct JixelEncoder<'a> {
49    writer: &'a mut dyn Write,
50    pub config: EncodeConfig,
51}
52
53fn default_config() -> EncodeConfig {
54    EncodeConfig {
55        speed: Speed::Slow,
56        ..EncodeConfig::default()
57    }
58    .with_distance(1.25)
59}
60
61impl<'a> JixelEncoder<'a> {
62    pub fn new(writer: &'a mut dyn Write) -> Self {
63        Self::with_config(writer, default_config())
64    }
65
66    pub fn with_config(writer: &'a mut dyn Write, config: EncodeConfig) -> Self {
67        Self { writer, config }
68    }
69
70    pub fn writer(&self) -> &(dyn Write + 'a) {
71        self.writer
72    }
73
74    pub fn writer_mut(&mut self) -> &mut (dyn Write + 'a) {
75        self.writer
76    }
77
78    pub fn into_inner(self) -> &'a mut dyn Write {
79        self.writer
80    }
81
82    /// Encodes a [`DynamicImage`] without converting its pixel format.
83    pub fn write_dynamic_image(self, image: &DynamicImage) -> ImageResult<()> {
84        ImageEncoder::write_image(
85            self,
86            image.as_bytes(),
87            image.width(),
88            image.height(),
89            image.color().into(),
90        )
91    }
92
93    fn encode(
94        &self,
95        buf: &[u8],
96        width: usize,
97        height: usize,
98        color_type: ExtendedColorType,
99    ) -> ImageResult<Vec<u8>> {
100        use ExtendedColorType::*;
101
102        let result = match color_type {
103            L8 => jixel::encode_image_gray(buf, width, height, &self.config),
104            La8 => encode_la8(buf, width, height, &self.config),
105            Rgb8 => jixel::encode_image(buf, width, height, &self.config),
106            Rgba8 => encode_rgba8(buf, width, height, &self.config),
107            L16 => {
108                let samples = native_u16(buf);
109                jixel::encode_image_gray_16bit(&samples, width, height, &self.config)
110            }
111            La16 => {
112                let samples = native_u16(buf);
113                encode_la16(&samples, width, height, &self.config)
114            }
115            Rgb16 => {
116                let samples = native_u16(buf);
117                jixel::encode_image_16bit(&samples, width, height, &self.config)
118            }
119            Rgba16 => {
120                let samples = native_u16(buf);
121                encode_rgba16(&samples, width, height, &self.config)
122            }
123            Rgb32F => {
124                let samples = native_f32(buf);
125                jixel::encode_image_f32(&samples, width, height, &self.config)
126            }
127            Rgba32F => {
128                let samples = native_f32(buf);
129                encode_rgba_f32(&samples, width, height, &self.config)
130            }
131            Bgr8 => {
132                let rgb = bgr_to_rgb(buf);
133                jixel::encode_image(&rgb, width, height, &self.config)
134            }
135            Bgra8 => encode_bgra8(buf, width, height, &self.config),
136            _ => return Err(unsupported_color(color_type)),
137        };
138
139        result.map_err(encoding_error)
140    }
141}
142
143impl ImageEncoder for JixelEncoder<'_> {
144    fn write_image(
145        self,
146        buf: &[u8],
147        width: u32,
148        height: u32,
149        color_type: ExtendedColorType,
150    ) -> ImageResult<()> {
151        let bits_per_pixel = u64::from(color_type.bits_per_pixel());
152        let row_len = (u64::from(width) * bits_per_pixel).div_ceil(8);
153        let expected = row_len.saturating_mul(u64::from(height));
154        if expected != buf.len() as u64 {
155            return Err(ImageError::Parameter(ParameterError::from_kind(
156                ParameterErrorKind::DimensionMismatch,
157            )));
158        }
159
160        let encoded = self.encode(buf, width as usize, height as usize, color_type)?;
161        self.writer.write_all(&encoded).map_err(ImageError::IoError)
162    }
163
164    fn set_icc_profile(&mut self, icc_profile: Vec<u8>) -> Result<(), UnsupportedError> {
165        self.config.icc_profile = Some(icc_profile);
166        Ok(())
167    }
168
169    fn set_exif_metadata(&mut self, exif: Vec<u8>) -> Result<(), UnsupportedError> {
170        self.config.exif = Some(exif);
171        Ok(())
172    }
173}
174
175fn encode_la8(
176    input: &[u8],
177    width: usize,
178    height: usize,
179    config: &EncodeConfig,
180) -> Result<Vec<u8>, jixel::EncodeError> {
181    if has_alpha::<_, 1, 2>(input, width, width * 2, u8::MAX) {
182        jixel::encode_image_gray_alpha(input, width, height, config)
183    } else {
184        let luma = discard_gray_alpha(input);
185        jixel::encode_image_gray(&luma, width, height, config)
186    }
187}
188
189fn encode_rgba8(
190    input: &[u8],
191    width: usize,
192    height: usize,
193    config: &EncodeConfig,
194) -> Result<Vec<u8>, jixel::EncodeError> {
195    if has_alpha::<_, 3, 4>(input, width, width * 4, u8::MAX) {
196        jixel::encode_image_with_alpha(input, width, height, config)
197    } else {
198        let rgb = discard_rgba_alpha(input);
199        jixel::encode_image(&rgb, width, height, config)
200    }
201}
202
203fn encode_la16(
204    input: &[u16],
205    width: usize,
206    height: usize,
207    config: &EncodeConfig,
208) -> Result<Vec<u8>, jixel::EncodeError> {
209    if has_alpha::<_, 1, 2>(input, width, width * 2, u16::MAX) {
210        jixel::encode_image_gray_alpha_16bit(input, width, height, config)
211    } else {
212        let luma = discard_gray_alpha(input);
213        jixel::encode_image_gray_16bit(&luma, width, height, config)
214    }
215}
216
217fn encode_rgba16(
218    input: &[u16],
219    width: usize,
220    height: usize,
221    config: &EncodeConfig,
222) -> Result<Vec<u8>, jixel::EncodeError> {
223    if has_alpha::<_, 3, 4>(input, width, width * 4, u16::MAX) {
224        jixel::encode_image_with_alpha_16bit(input, width, height, config)
225    } else {
226        let rgb = discard_rgba_alpha(input);
227        jixel::encode_image_16bit(&rgb, width, height, config)
228    }
229}
230
231fn encode_rgba_f32(
232    input: &[f32],
233    width: usize,
234    height: usize,
235    config: &EncodeConfig,
236) -> Result<Vec<u8>, jixel::EncodeError> {
237    if has_alpha::<_, 3, 4>(input, width, width * 4, 1.0) {
238        jixel::encode_image_with_alpha_f32(input, width, height, config)
239    } else {
240        let rgb = discard_rgba_alpha(input);
241        jixel::encode_image_f32(&rgb, width, height, config)
242    }
243}
244
245fn encode_bgra8(
246    input: &[u8],
247    width: usize,
248    height: usize,
249    config: &EncodeConfig,
250) -> Result<Vec<u8>, jixel::EncodeError> {
251    let has_transparency = has_alpha::<_, 3, 4>(input, width, width * 4, u8::MAX);
252    let reordered = bgra_to_rgba(input);
253    if has_transparency {
254        jixel::encode_image_with_alpha(&reordered, width, height, config)
255    } else {
256        let rgb = discard_rgba_alpha(&reordered);
257        jixel::encode_image(&rgb, width, height, config)
258    }
259}
260
261fn native_u16(buf: &[u8]) -> Vec<u16> {
262    buf.as_chunks::<2>()
263        .0
264        .iter()
265        .map(|sample| u16::from_ne_bytes([sample[0], sample[1]]))
266        .collect()
267}
268
269fn native_f32(buf: &[u8]) -> Vec<f32> {
270    buf.as_chunks::<4>()
271        .0
272        .iter()
273        .map(|sample| f32::from_ne_bytes([sample[0], sample[1], sample[2], sample[3]]))
274        .collect()
275}
276
277fn discard_gray_alpha<T: Copy + Default>(input: &[T]) -> Vec<T> {
278    let pixels = input.as_chunks::<2>().0;
279    let mut output = vec![T::default(); pixels.len()];
280    for (dst, src) in output.iter_mut().zip(pixels) {
281        *dst = src[0];
282    }
283    output
284}
285
286fn discard_rgba_alpha<T: Copy + Default>(input: &[T]) -> Vec<T> {
287    let pixels = input.as_chunks::<4>().0;
288    let mut output = vec![T::default(); pixels.len() * 3];
289    for (dst, src) in output.as_chunks_mut::<3>().0.iter_mut().zip(pixels) {
290        dst[0] = src[0];
291        dst[1] = src[1];
292        dst[2] = src[2];
293    }
294    output
295}
296
297fn bgr_to_rgb(input: &[u8]) -> Vec<u8> {
298    let input_pixels = input.as_chunks::<3>().0;
299    let mut output = vec![0; input_pixels.len() * 3];
300    for (dst, src) in output.as_chunks_mut::<3>().0.iter_mut().zip(input_pixels) {
301        dst[0] = src[2];
302        dst[1] = src[1];
303        dst[2] = src[0];
304    }
305    output
306}
307
308fn bgra_to_rgba(input: &[u8]) -> Vec<u8> {
309    let input_pixels = input.as_chunks::<4>().0;
310    let mut output = vec![0; input_pixels.len() * 4];
311    for (dst, src) in output.as_chunks_mut::<4>().0.iter_mut().zip(input_pixels) {
312        dst[0] = src[2];
313        dst[1] = src[1];
314        dst[2] = src[0];
315        dst[3] = src[3];
316    }
317    output
318}
319
320fn format_hint() -> ImageFormatHint {
321    ImageFormatHint::Name("JPEG XL".to_owned())
322}
323
324fn encoding_error(error: jixel::EncodeError) -> ImageError {
325    ImageError::Encoding(EncodingError::new(format_hint(), error))
326}
327
328fn unsupported_color(color_type: ExtendedColorType) -> ImageError {
329    ImageError::Unsupported(UnsupportedError::from_format_and_kind(
330        format_hint(),
331        UnsupportedErrorKind::Color(color_type),
332    ))
333}
334
335#[cfg(test)]
336mod tests {
337    use super::*;
338
339    fn native_bytes_u16(samples: &[u16]) -> Vec<u8> {
340        samples
341            .iter()
342            .flat_map(|sample| sample.to_ne_bytes())
343            .collect()
344    }
345
346    #[test]
347    fn opaque_la16_is_encoded_as_l16() {
348        let la = [100u16, u16::MAX, 200, u16::MAX];
349        let expected =
350            jixel::encode_image_gray_16bit(&[100, 200], 2, 1, &default_config()).unwrap();
351        let mut actual = Vec::new();
352
353        JixelEncoder::new(&mut actual)
354            .write_image(&native_bytes_u16(&la), 2, 1, ExtendedColorType::La16)
355            .unwrap();
356
357        assert_eq!(actual, expected);
358    }
359
360    #[test]
361    fn bgr_is_reordered() {
362        let mut actual = Vec::new();
363        JixelEncoder::new(&mut actual)
364            .write_image(&[30, 20, 10], 1, 1, ExtendedColorType::Bgr8)
365            .unwrap();
366        let expected = jixel::encode_image(&[10, 20, 30], 1, 1, &default_config()).unwrap();
367        assert_eq!(actual, expected);
368    }
369
370    #[test]
371    fn translucent_bgra_is_reordered_with_alpha() {
372        let mut actual = Vec::new();
373        JixelEncoder::new(&mut actual)
374            .write_image(&[30, 20, 10, 128], 1, 1, ExtendedColorType::Bgra8)
375            .unwrap();
376        let expected =
377            jixel::encode_image_with_alpha(&[10, 20, 30, 128], 1, 1, &default_config()).unwrap();
378        assert_eq!(actual, expected);
379    }
380
381    #[test]
382    fn image_encoder_metadata_updates_config() {
383        let mut output = Vec::new();
384        let mut encoder = JixelEncoder::new(&mut output);
385        encoder.set_icc_profile(vec![1, 2, 3]).unwrap();
386        encoder.set_exif_metadata(vec![4, 5, 6]).unwrap();
387        assert_eq!(encoder.config.icc_profile, Some(vec![1, 2, 3]));
388        assert_eq!(encoder.config.exif, Some(vec![4, 5, 6]));
389    }
390
391    #[test]
392    fn unsupported_color_reports_image_error() {
393        let mut output = Vec::new();
394        let error = JixelEncoder::new(&mut output)
395            .write_image(&[0], 1, 1, ExtendedColorType::A8)
396            .unwrap_err();
397        assert!(matches!(error, ImageError::Unsupported(_)));
398    }
399
400    #[test]
401    fn invalid_buffer_length_returns_dimension_mismatch() {
402        let mut output = Vec::new();
403        let error = JixelEncoder::new(&mut output)
404            .write_image(&[0, 1], 1, 1, ExtendedColorType::Rgb8)
405            .unwrap_err();
406
407        let ImageError::Parameter(error) = error else {
408            panic!("expected a parameter error");
409        };
410        assert_eq!(error.kind(), ParameterErrorKind::DimensionMismatch);
411        assert!(output.is_empty());
412    }
413
414    #[test]
415    fn dynamic_image_is_encoded_directly() {
416        let image = DynamicImage::ImageRgba8(
417            image::RgbaImage::from_raw(2, 1, vec![10, 20, 30, 255, 40, 50, 60, 128]).unwrap(),
418        );
419        let mut expected = Vec::new();
420        JixelEncoder::new(&mut expected)
421            .write_image(
422                image.as_bytes(),
423                image.width(),
424                image.height(),
425                image.color().into(),
426            )
427            .unwrap();
428
429        let mut actual = Vec::new();
430        JixelEncoder::new(&mut actual)
431            .write_dynamic_image(&image)
432            .unwrap();
433
434        assert_eq!(actual, expected);
435    }
436}