Skip to main content

pillow_rs/ops/
convert.rs

1use std::borrow::Cow;
2
3use crate::color;
4use crate::error::PilError;
5use crate::image::{Image, PipelineOps};
6use crate::pipeline::{ColorMode, DitherMethod, PipelineOp};
7use crate::raster::{DynamicImage, GenericImageView};
8
9/// Parses a Pillow mode string into a pipeline color mode.
10///
11/// # Errors
12///
13/// Returns [`PilError::ValueError`] when `s` is not one of the modes supported
14/// by core conversion.
15pub fn parse_mode(s: &str) -> Result<ColorMode, PilError> {
16    match s {
17        "L" => Ok(ColorMode::L),
18        "LA" => Ok(ColorMode::LA),
19        "RGB" => Ok(ColorMode::RGB),
20        "RGBA" => Ok(ColorMode::RGBA),
21        "CMYK" => Ok(ColorMode::CMYK),
22        "YCbCr" => Ok(ColorMode::YCbCr),
23        "HSV" => Ok(ColorMode::HSV),
24        "I" => Ok(ColorMode::I),
25        "F" => Ok(ColorMode::F),
26        "P" => Ok(ColorMode::P),
27        "1" => Ok(ColorMode::Mode1),
28        _ => Err(PilError::ValueError(format!("Unknown mode: {}", s))),
29    }
30}
31
32fn is_luma16_mode(mode: &str) -> bool {
33    matches!(mode, "I;16" | "I;16L" | "I;16B" | "I;16N")
34}
35
36/// Modes that require special handling when converting FROM them.
37/// These modes store pixel data in a non-standard interpretation within
38/// standard DynamicImage variants (e.g., CMYK values stored as RGBA).
39fn is_nonstandard_mode(mode: &str) -> bool {
40    matches!(mode, "CMYK" | "HSV" | "YCbCr" | "I" | "F" | "P" | "PA")
41}
42
43/// Extracts the Y band of a YCbCr image as luma bytes.
44///
45/// Pillow's C converter (`src/libImaging/Convert.c`) maps YCbCr to L and "1"
46/// through the Y channel directly rather than through the RGB luminance.
47fn ycbcr_luma8(img: &crate::raster::DynamicImage) -> crate::raster::GrayImage {
48    let rgb = img.to_rgb8();
49    crate::raster::GrayImage::from_fn(rgb.width(), rgb.height(), |x, y| {
50        crate::raster::Luma([rgb.get_pixel(x, y)[0]])
51    })
52}
53
54/// Per-entry alpha table Pillow applies when converting a palette image to an
55/// alpha band: a single transparent index becomes 0 with everything else 255,
56/// a PNG `tRNS` table is used verbatim.
57fn palette_alpha_for_convert(img: &Image) -> Option<Vec<u8>> {
58    if let Some(transparency) = img.pending_palette_transparency() {
59        return match transparency {
60            crate::image::PaletteTransparency::Index(index) => {
61                let mut table = vec![255u8; 256];
62                table[usize::from(index)] = 0;
63                Some(table)
64            }
65            crate::image::PaletteTransparency::Table(alpha) => Some(alpha),
66        };
67    }
68    // `putpalette(..., rawmode="RGBA")` stores attached alpha on the
69    // committed palette rather than in pending `info["transparency"]`.
70    // Pillow's P->LA conversion consumes both representations.
71    img.palette_alpha().filter(|alpha| !alpha.is_empty())
72}
73
74fn parse_dither(s: Option<&str>) -> Result<Option<DitherMethod>, PilError> {
75    match s {
76        Some("NONE") | Some("none") => Ok(Some(DitherMethod::None)),
77        Some("FLOYDSTEINBERG") | Some("floydsteinberg") => Ok(Some(DitherMethod::FloydSteinberg)),
78        None => Ok(Some(DitherMethod::FloydSteinberg)), // PIL default: FloydSteinberg dither
79        // Pillow's Python converter rejects string dither values before the C
80        // converter interprets the integer enum.
81        _ => Err(PilError::TypeError(
82            "'str' object cannot be interpreted as an integer".into(),
83        )),
84    }
85}
86
87/// Host-neutral Python-facing dither input.
88#[derive(Debug, Clone)]
89pub enum PythonDitherInput {
90    /// No dither argument was supplied.
91    None,
92    /// Python integer enum; zero disables dithering and non-zero selects
93    /// Floyd-Steinberg.
94    Integer(u32),
95    /// Python string, which Pillow rejects for this entry point.
96    Name(String),
97    /// A value of another host type. The type name is used in Pillow's
98    /// compatibility diagnostic.
99    Invalid(String),
100}
101
102/// Validates a Python-facing dither argument that arrived as a string.
103///
104/// Pillow's Python API accepts the dither enum as an integer, even though the
105/// shared Rust/JavaScript API uses symbolic strings internally. Parse the
106/// symbolic value through the same core helper, then preserve Pillow's Python
107/// type error for the host string input.
108///
109/// # Errors
110///
111/// Always returns [`PilError::TypeError`] because Python strings are not valid
112/// dither enum arguments.
113pub fn validate_python_convert_dither(value: &str) -> Result<(), PilError> {
114    let _ = parse_dither(Some(value));
115    Err(PilError::TypeError(
116        "'str' object cannot be interpreted as an integer".into(),
117    ))
118}
119
120/// Normalizes a Python-facing dither value into the symbolic core form.
121pub fn normalize_python_convert_dither(
122    value: PythonDitherInput,
123) -> Result<Option<String>, PilError> {
124    match value {
125        PythonDitherInput::None => Ok(None),
126        PythonDitherInput::Integer(value) => Ok(Some(if value == 0 {
127            "NONE".to_owned()
128        } else {
129            "FLOYDSTEINBERG".to_owned()
130        })),
131        PythonDitherInput::Name(value) => validate_python_convert_dither(&value).map(|_| None),
132        PythonDitherInput::Invalid(type_name) => Err(PilError::TypeError(format!(
133            "'{type_name}' object cannot be interpreted as an integer"
134        ))),
135    }
136}
137
138/// Host-neutral destination mode input for the Python conversion wrapper.
139#[derive(Debug, Clone)]
140pub enum PythonConvertModeInput {
141    /// No destination mode was supplied.
142    None,
143    /// A destination mode name.
144    Name(String),
145    /// A value of another host type.
146    Invalid(String),
147}
148
149/// Host-neutral palette input for the Python conversion wrapper.
150#[derive(Debug, Clone)]
151pub enum PythonConvertPaletteInput {
152    /// No palette object was supplied.
153    None,
154    /// A symbolic palette name.
155    Name(String),
156    /// A value of another host type.
157    Invalid(String),
158}
159
160/// Pillow-compatible image mode conversion methods.
161impl Image {
162    /// Applies Python's default-mode, palette, and matrix validation before
163    /// entering the shared conversion implementation.
164    pub fn convert_with_input(
165        &self,
166        mode: PythonConvertModeInput,
167        matrix: Option<Vec<f64>>,
168        dither: PythonDitherInput,
169        palette: PythonConvertPaletteInput,
170        colors: Option<u32>,
171    ) -> Result<Image, PilError> {
172        let source_mode = self.mode()?;
173        let target_mode = match mode {
174            PythonConvertModeInput::None => {
175                if source_mode != "P" {
176                    return Ok(self.copy());
177                }
178                let mut target = self.palette_mode().unwrap_or("RGB").to_owned();
179                if target == "RGB" && self.has_transparency_data() {
180                    target = "RGBA".to_owned();
181                }
182                target
183            }
184            PythonConvertModeInput::Name(target) => target,
185            PythonConvertModeInput::Invalid(type_name) => {
186                return Err(PilError::TypeError(format!(
187                    "argument 1 must be str, not {type_name}"
188                )));
189            }
190        };
191
192        if target_mode == source_mode && matrix.is_none() {
193            return Ok(self.copy());
194        }
195        // Pillow rejects matrix conversions to unsupported target modes before
196        // it validates the coefficient count. This ordering is observable for
197        // an invalid mode paired with a short matrix.
198        if matrix.is_some() && !matches!(target_mode.as_str(), "L" | "RGB") {
199            return Err(PilError::ValueError("illegal conversion".to_owned()));
200        }
201        if let Some(matrix) = matrix.as_ref() {
202            if !matches!(matrix.len(), 4 | 12) {
203                return Err(PilError::TypeError(format!(
204                    "argument 2 must be sequence of length 12, not {}",
205                    matrix.len()
206                )));
207            }
208        }
209
210        let palette = match palette {
211            PythonConvertPaletteInput::None => None,
212            PythonConvertPaletteInput::Name(name) => Some(name),
213            // Pillow accepts and ignores palette values for the public
214            // conversion paths exercised here; only the target mode and
215            // dither/matrix inputs affect conversion dispatch.
216            PythonConvertPaletteInput::Invalid(_) => None,
217        };
218        // Keep Python's dither coercion in the Rust core. Pillow ignores the
219        // argument on a same-mode no-op and on matrix conversions, and reports
220        // matrix/mode errors before it attempts to interpret the dither enum.
221        let dither = if matrix.is_some() {
222            None
223        } else {
224            normalize_python_convert_dither(dither)?
225        };
226        self.convert(
227            &target_mode,
228            matrix,
229            dither.as_deref(),
230            palette.as_deref(),
231            colors,
232        )
233    }
234
235    /// Converts this image to another Pillow mode.
236    ///
237    /// # Inputs
238    ///
239    /// - `mode`: destination Pillow mode, such as `"L"`, `"RGB"`, `"RGBA"`,
240    ///   `"CMYK"`, `"HSV"`, `"YCbCr"`, `"I"`, `"F"`, `"P"`, or `"1"`.
241    /// - `matrix`: optional Pillow conversion matrix for immediate conversion.
242    ///   Four values convert RGB input to luma; twelve values convert RGB input
243    ///   through a 3x4 color matrix.
244    /// - `dither`: optional dither name for binary and palette-like conversion.
245    ///
246    /// # Returns
247    ///
248    /// A new [`Image`] tagged with the destination mode. Matrix conversions
249    /// execute immediately; mode-only conversions may be represented lazily in
250    /// the pipeline.
251    ///
252    /// # Errors
253    ///
254    /// Returns [`PilError`] when the mode, matrix, dither option, or source
255    /// image data is invalid.
256    pub fn convert(
257        &self,
258        mode: &str,
259        matrix: Option<Vec<f64>>,
260        dither: Option<&str>,
261        _palette: Option<&str>,
262        _colors: Option<u32>,
263    ) -> Result<Image, PilError> {
264        let src_mode = self.mode()?;
265        if src_mode == "La" && !matches!(mode, "La" | "LA") && matrix.is_none() {
266            // Only La->LA has a direct converter. All other destinations
267            // retry through the L base, which Pillow cannot produce from La.
268            return Err(PilError::ValueError(
269                "conversion from La to L not supported".into(),
270            ));
271        }
272        // Validate the target before source-specific conversion dispatch. The
273        // Python wrapper used to reject unknown modes first, which made this
274        // public Rust error path unreachable and allowed an unknown target to
275        // slip through for some non-standard source modes. PA is handled by
276        // the explicit palette-alpha path below but is not a ColorMode enum.
277        if !matches!(mode, "PA" | "RGBX" | "RGBa" | "La" | "LAB") && !is_luma16_mode(mode) {
278            parse_mode(mode).map_err(|_| PilError::ValueError("image has wrong mode".into()))?;
279        }
280
281        // Pillow stores bilevel "1" pixels as 0/255; our core keeps the raw
282        // 0/1 bytes, so every conversion FROM "1" must map 1 -> 255 first
283        // (Pillow's convert treats "1" as "L" through the luma path).
284        if src_mode == "1" && mode != "1" {
285            let img = self.materialize()?;
286            let mut gray = crate::raster::GrayImage::new(img.width(), img.height());
287            for (op, ip) in gray.pixels_mut().zip(img.to_luma8().pixels()) {
288                op[0] = if ip[0] != 0 { 255 } else { 0 };
289            }
290            let expanded = crate::raster::DynamicImage::ImageLuma8(gray);
291            return Image::from_dynamic(expanded, None).convert(mode, matrix, dither, None, None);
292        }
293
294        // Matrix-based conversion must be executed even when the requested
295        // mode equals the source mode. Pillow applies the matrix before its
296        // same-mode fast path; returning a copy first silently discarded the
297        // matrix and made RGB->RGB conversion diverge.
298        if let Some(mat) = matrix {
299            let img = self.materialize()?;
300            return convert_with_matrix(&img, mode, &mat)
301                .map(|result| Image::from_dynamic(result, explicit_mode_for(mode)));
302        }
303
304        // CMYK shares the RGBA-sized transport but stores C/M/Y/K, not
305        // red/green/blue/alpha. Keep this conversion lazy so the executors
306        // can consume native CMYK channels with Pillow's exact integer math.
307        if src_mode == "CMYK" && mode == "RGB" {
308            return Ok(Image::push_op(
309                self,
310                PipelineOp::Convert {
311                    mode: ColorMode::RGB,
312                    matrix: None,
313                    dither: None,
314                },
315            ));
316        }
317
318        if mode == src_mode {
319            return Ok(self.copy());
320        }
321
322        if mode == "LAB" {
323            // Pillow's LAB converter consumes RGB samples. Unsigned-16 luma
324            // has no direct LAB converter, so follow Pillow's clipped L
325            // fallback before expanding to RGB; every other source uses its
326            // existing RGB conversion path (palette, scalar, alpha, and
327            // non-standard source handling included).
328            let rgb = if is_luma16_mode(&src_mode) {
329                self.convert("L", None, None, None, None)?
330                    .convert("RGB", None, None, None, None)?
331            } else {
332                self.convert("RGB", None, None, None, None)?
333            };
334            let mut result = Image::push_op(
335                &rgb,
336                PipelineOp::ConvertLab {
337                    icc_profile: crate::lab::pillow_lab_icc_profile().into(),
338                },
339            );
340            if let Image::Pipeline { explicit_mode, .. } = &mut result {
341                *explicit_mode = Some("LAB".to_owned());
342            }
343            return Ok(result);
344        }
345
346        if src_mode == "La" || (src_mode == "RGBa" && !matches!(mode, "P" | "PA")) {
347            let straight =
348                crate::ops::pil_resize::unpremultiply_alpha(self.materialized_shared()?.as_ref());
349            if matches!((src_mode.as_str(), mode), ("La", "LA") | ("RGBa", "RGBA")) {
350                return Ok(Image::from_dynamic(straight, None));
351            }
352            // RGBa has a direct RGB converter. Its other destinations retry
353            // through RGB, so a later LA conversion installs opaque alpha.
354            return Image::from_dynamic(DynamicImage::ImageRgb8(straight.to_rgb8()), None)
355                .convert(mode, None, dither, _palette, _colors);
356        }
357        // RGBa has direct palette converters that quantize its stored RGB
358        // samples; unlike the RGB fallback they do not unpremultiply first.
359
360        if matches!(mode, "RGBa" | "La") {
361            if src_mode == "P" {
362                return Err(PilError::ValueError("conversion not supported".into()));
363            }
364            if matches!((src_mode.as_str(), mode), ("RGBA", "RGBa") | ("LA", "La")) {
365                let premultiplied =
366                    crate::ops::pil_resize::premultiply_alpha(self.materialized_shared()?.as_ref());
367                return Ok(Image::from_dynamic(premultiplied, Some(mode.to_owned())));
368            }
369            if matches!(src_mode.as_str(), "1" | "L" | "LA" | "I" | "F")
370                || is_luma16_mode(&src_mode)
371            {
372                return Err(PilError::ValueError(format!(
373                    "conversion from L to {mode} not supported"
374                )));
375            }
376            // RGB has direct opaque RGBa/La converters. RGBA->La and the
377            // other color modes first normalize to RGB, discarding alpha.
378            let rgb = self.convert("RGB", None, dither, _palette, _colors)?;
379            let rgb = rgb.materialized_shared()?;
380            let converted = if mode == "RGBa" {
381                DynamicImage::ImageRgba8(rgb.to_rgba8())
382            } else {
383                DynamicImage::ImageLumaA8(color::pil_grayscale_alpha(&rgb)?)
384            };
385            return Ok(Image::from_dynamic(converted, Some(mode.to_owned())));
386        }
387
388        if mode == "RGBX" {
389            // LA/PA preserve their alpha in X; RGBA's direct converter
390            // instead supplies 255. Palette X consumes attached palette
391            // alpha, but does not promote info["transparency"].
392            let target = if matches!(src_mode.as_str(), "LA" | "PA") {
393                "RGBA"
394            } else {
395                "RGB"
396            };
397            let converted = self.convert(target, None, dither, _palette, _colors)?;
398            let mut rgba = converted.materialized_shared()?.to_rgba8();
399            if src_mode == "P" {
400                if let Some(alpha) = self.palette_alpha() {
401                    let indices = self.materialized_shared()?;
402                    for (pixel, &index) in rgba.pixels_mut().zip(indices.as_bytes()) {
403                        pixel[3] = alpha.get(usize::from(index)).copied().unwrap_or(255);
404                    }
405                }
406            }
407            return Ok(Image::from_dynamic(
408                DynamicImage::ImageRgba8(rgba),
409                Some(mode.to_owned()),
410            ));
411        }
412
413        if src_mode == "PA" && mode == "P" {
414            // Dropping PA alpha preserves indices and the existing palette;
415            // expanding and requantizing colors can change both.
416            return Ok(Image::Loaded(crate::image::LoadedData {
417                image: std::sync::Arc::new(DynamicImage::ImageLuma8(
418                    self.materialized_shared()?.to_luma8(),
419                )),
420                known_zero_fill: false,
421                explicit_mode: Some("P".to_owned()),
422                decoded_mode: crate::raster::ColorType::L8.into(),
423                palette: self.palette(),
424                palette_alpha: self.palette_alpha(),
425                source_format: self.source_format(),
426                info: self.image_info(),
427                exif: self.exif_metadata(),
428            }));
429        }
430
431        if is_luma16_mode(&src_mode) && matches!(mode, "I" | "F" | "P" | "PA" | "HSV" | "YCbCr") {
432            if src_mode != "I;16N" && matches!(mode, "I" | "F") {
433                let source = self.materialized_shared()?;
434                let DynamicImage::ImageLuma16(samples) = source.as_ref() else {
435                    return Err(PilError::InternalError(
436                        "invalid unsigned-16 storage".into(),
437                    ));
438                };
439                let mut result = crate::raster::RgbaImage::new(samples.width(), samples.height());
440                for (output, sample) in result.pixels_mut().zip(samples.pixels()) {
441                    // I;16/I;16L/I;16B have direct numeric I/F converters.
442                    // I;16N retries through L, clipping before widening.
443                    output.0 = if mode == "I" {
444                        i32::from(sample[0]).to_le_bytes()
445                    } else {
446                        f32::from(sample[0]).to_le_bytes()
447                    };
448                }
449                return Ok(Image::from_dynamic(
450                    DynamicImage::ImageRgba8(result),
451                    Some(mode.to_owned()),
452                ));
453            }
454            // The remaining destinations retry through clipped L. Palette
455            // results use identity gray indices; YCbCr copies that L sample
456            // rather than recomputing Y from an RGB expansion.
457            let luma = self.convert("L", None, None, None, None)?;
458            return luma.convert(mode, None, dither, _palette, _colors);
459        }
460
461        // Pillow's typed I;16 converters consume an 8-bit luma sample as the
462        // same numeric unsigned word; they do not expand 17 to 0x1111 like
463        // the generic image-raster u8→u16 conversion.  Keep this destination
464        // path eager so the logical mode tag and declared byte order survive
465        // without adding a byte-oriented ColorMode variant to PipelineOp.
466        if is_luma16_mode(mode) {
467            if src_mode == "P" {
468                // Pillow's palette converter has no direct I;16 destination
469                // and reports this exact conversion error before Paste.c.
470                return Err(PilError::ValueError("conversion not supported".into()));
471            }
472            let samples = if src_mode == "I" && mode != "I;16N" {
473                // Pillow's I→I;16/I;16L/I;16B converter is the one typed
474                // scalar path: clamp the signed 32-bit sample to 0..65535.
475                // I;16N on the little-endian oracle has only the byte-domain
476                // converter, so it intentionally falls through to L below.
477                let image = self.materialize()?;
478                let (width, height) = image.dimensions();
479                let raw = image.as_bytes();
480                let samples = raw.chunks_exact(4).map(|bytes| {
481                    let value = i32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
482                    value.clamp(0, i32::from(u16::MAX)) as u16
483                });
484                crate::raster::ImageBuffer::from_raw(width, height, samples.collect()).ok_or_else(
485                    || PilError::InternalError("I;16 conversion buffer shape mismatch".into()),
486                )?
487            } else {
488                // YCbCr has a direct Y-band converter only for L/LA. Its
489                // unsigned-16 destinations retry through RGB before luma.
490                let source = if src_mode == "YCbCr" {
491                    self.convert("RGB", None, None, None, None)?
492                } else {
493                    self.clone()
494                };
495                let luma = source
496                    .convert("L", None, None, None, None)?
497                    .materialize()?
498                    .to_luma8();
499                let (width, height) = luma.dimensions();
500                crate::raster::ImageBuffer::from_fn(width, height, |x, y| {
501                    crate::raster::Luma([u16::from(luma.get_pixel(x, y)[0])])
502                })
503            };
504            return Ok(Image::from_dynamic(
505                DynamicImage::ImageLuma16(samples),
506                Some(mode.to_owned()),
507            ));
508        }
509        // Handle conversion from non-standard modes (CMYK, HSV, YCbCr, I, F, P).
510        // These modes store pixel data in standard DynamicImage containers but with
511        // a different interpretation (e.g., CMYK values stored as RGBA). We must
512        // materialize first and convert using PIL's exact algorithms.
513        // Lazy Bytes images report no explicit mode; fall back to the decoded
514        // mode so non-standard sources (P, CMYK, I, F, HSV, YCbCr) take the
515        // palette/transparency-aware conversion path even before load().
516        let effective_src_mode = self
517            .explicit_mode()
518            .map(str::to_owned)
519            .unwrap_or_else(|| src_mode.clone());
520        let effective_src_mode_name = effective_src_mode.as_str();
521
522        // Pillow's Image.convert first tries the direct I/F converter when
523        // one exists, then retries unsupported destinations through the
524        // source mode's base type, which is L.  Normalizing these scalar
525        // modes through RGB changes Pillow's fixed-point behavior (for
526        // example, RGB(11, 11, 11) has Y=10 while F(11.5) truncates to an
527        // L value of 11 before a YCbCr conversion).
528        // PA is a dedicated indexed-plus-alpha destination; route I/F through
529        // convert_to_palette_alpha below so scalar samples use its direct
530        // clamped-index conversion instead of the generic L fallback.
531        if matches!(effective_src_mode_name, "I" | "F") && mode == "L" {
532            // The scalar-to-L converters only read the packed four-byte
533            // carrier. Share the already materialized source instead of
534            // materialize() cloning its full buffer before the conversion.
535            let img = self.materialized_shared_for_ops()?;
536            let luma = if effective_src_mode_name == "I" {
537                color::i_to_l(img.as_ref())
538            } else if !cfg!(feature = "parallel")
539                && crate::compute::Backend::pipeline_telemetry_enabled()
540                && matches!(
541                    crate::compute::preferred_active_backend()?,
542                    Some((crate::compute::Backend::Cpu, _))
543                )
544            {
545                crate::compute::execute_eager_cpu_image_operation(
546                    "Convert",
547                    img.as_ref(),
548                    true,
549                    || Ok(color::f_to_l(img.as_ref())),
550                )?
551            } else {
552                color::f_to_l(img.as_ref())
553            };
554            return Ok(Image::from_dynamic(luma, None));
555        }
556        if effective_src_mode_name == "F" && mode == "I" {
557            // f_to_i only reads the packed scalar carrier. Share the already
558            // materialized source instead of cloning its full buffer first.
559            let img = self.materialized_shared_for_ops()?;
560            let converted = if !cfg!(feature = "parallel")
561                && crate::compute::Backend::pipeline_telemetry_enabled()
562                && matches!(
563                    crate::compute::preferred_active_backend()?,
564                    Some((crate::compute::Backend::Cpu, _))
565                ) {
566                crate::compute::execute_eager_cpu_image_operation(
567                    "Convert",
568                    img.as_ref(),
569                    true,
570                    || Ok(color::f_to_i(img.as_ref())),
571                )?
572            } else {
573                color::f_to_i(img.as_ref())
574            };
575            return Ok(Image::from_dynamic(converted, explicit_mode_for(mode)));
576        }
577        if matches!(effective_src_mode_name, "I" | "F") && mode != "PA" {
578            let img = self.materialize()?;
579            let result = match (effective_src_mode_name, mode) {
580                ("I", "F") => color::i_to_f(&img),
581                ("I", "RGB") => color::i_to_rgb(&img),
582                ("F", "I") => color::f_to_i(&img),
583                ("F", "RGB") => color::f_to_rgb(&img),
584                _ => {
585                    let luma = if effective_src_mode_name == "I" {
586                        color::i_to_l(&img)
587                    } else {
588                        color::f_to_l(&img)
589                    };
590                    return Image::from_dynamic(luma, None)
591                        .convert(mode, matrix, dither, None, _colors);
592                }
593            };
594            return Ok(Image::from_dynamic(result, explicit_mode_for(mode)));
595        }
596
597        // Pillow's Convert.c first reinterprets non-standard source storage
598        // as RGB whenever the destination is another non-standard family.
599        // The deferred scalar converter only sees the destination mode, so
600        // passing raw CMYK/HSV/YCbCr/I/F bytes through would treat those bytes
601        // as ordinary RGB samples. Normalize the source through the public
602        // RGB representation before dispatching HSV, YCbCr, P, I, or F.
603        // CMYK->I/F retains its dedicated exact path below.
604        if is_nonstandard_mode(effective_src_mode_name)
605            && matches!(mode, "HSV" | "YCbCr" | "P" | "I" | "F")
606            && mode != effective_src_mode_name
607            && !(effective_src_mode_name == "CMYK" && matches!(mode, "I" | "F"))
608        {
609            let palette = self.palette();
610            let img = self.materialize()?;
611            let converted = if effective_src_mode_name == "PA" {
612                crate::image::expand_palette_alpha(
613                    &img.to_luma_alpha8(),
614                    palette.as_deref().unwrap_or_default(),
615                )
616            } else {
617                color::convert_from_nonstandard(effective_src_mode_name, &img, palette.as_deref())
618                    .unwrap_or_else(|| img.to_rgb8().into())
619            };
620            let rgb_source = Image::from_dynamic(converted, None);
621            return rgb_source.convert(mode, matrix, dither, None, _colors);
622        }
623
624        // `PA` is a real Pillow destination mode even though it is not one
625        // of the scalar pipeline modes.  Its conversion is not a generic
626        // mode tag: Pillow builds palette indices and a second, per-pixel
627        // alpha band.  Resolve it eagerly so standard and non-standard source
628        // modes follow the same public conversion contract.
629        if mode == "PA" {
630            let dither_enum = parse_dither(dither)?;
631            return convert_to_palette_alpha(self, effective_src_mode_name, dither_enum);
632        }
633
634        // Pillow routes unsigned 16-bit luma to the grayscale CMYK branch:
635        // C=M=Y=0 and K=255 minus the clipped luma sample. The ordinary
636        // packed converter cannot distinguish this source from RGB storage,
637        // so materialize the native samples before queuing the operation.
638        if mode == "CMYK"
639            && matches!(
640                effective_src_mode_name,
641                "I;16" | "I;16L" | "I;16B" | "I;16N"
642            )
643        {
644            let gray = self.materialize()?.to_luma8();
645            let (width, height) = gray.dimensions();
646            let mut result = crate::raster::RgbaImage::new(width, height);
647            for (output, input) in result.pixels_mut().zip(gray.pixels()) {
648                *output = crate::raster::Rgba([0, 0, 0, 255u8.saturating_sub(input[0])]);
649            }
650            return Ok(Image::from_dynamic(
651                DynamicImage::ImageRgba8(result),
652                explicit_mode_for(mode),
653            ));
654        }
655
656        let target_is_standard = !is_nonstandard_mode(mode);
657        // Non-standard sources must be materialized and converted to RGB
658        // before reaching a standard target OR a CMYK target (Pillow's
659        // CMYK inverse runs on the RGB values).  CMYK->CMYK is identity.
660        if is_nonstandard_mode(effective_src_mode_name)
661            && (target_is_standard
662                || mode == "CMYK"
663                || (mode == "PA" && effective_src_mode_name == "P"))
664            // PA→RGB can use the ordinary native byte converter after the
665            // pipeline evaluator expands its indexed samples through the
666            // retained palette.  Keep this one conversion lazy so SIMD/GPU
667            // adapters receive the same RGBA layout as every other RGB
668            // source; all other PA destinations still need the eager,
669            // mode-specific conversion below.
670            && !(effective_src_mode_name == "PA" && mode == "RGB")
671        {
672            let src_mode = effective_src_mode_name;
673            // Extract palette before materializing (P-mode palette may be on Pipeline)
674            let palette = self.palette();
675            // Conversion helpers only read the source. Keep the validated
676            // materialized buffer shared instead of cloning the whole frame;
677            // output conversion below owns its own result where required.
678            let shared = self.materialized_shared_for_ops()?;
679            let img = shared.as_ref();
680            if src_mode == "PA" && mode == "RGBA" {
681                // PA pixels are already stored as native [index, alpha]
682                // samples. Expand the borrowed bands straight into the
683                // requested owned RGBA result.
684                if let DynamicImage::ImageLumaA8(indices_alpha) = img {
685                    let expanded = crate::image::expand_palette_alpha(
686                        indices_alpha,
687                        palette.as_deref().unwrap_or_default(),
688                    );
689                    return Ok(Image::from_dynamic(expanded, explicit_mode_for(mode)));
690                }
691            }
692            let converted = if src_mode == "PA" {
693                // PA stores a palette index and a per-pixel alpha byte.
694                // Expand both before grayscale/CMYK conversion; treating
695                // the index as luma makes an unpaletted PA image produce
696                // visible color where Pillow correctly returns black.
697                crate::image::expand_palette_alpha(
698                    &img.to_luma_alpha8(),
699                    palette.as_deref().unwrap_or_default(),
700                )
701            } else {
702                color::convert_from_nonstandard(src_mode, img, palette.as_deref())
703                    .unwrap_or_else(|| img.to_rgb8().into())
704            };
705            // For mode "L" etc., derive from the RGB result.
706            let result = if mode == "CMYK" {
707                // I/F sources return through the scalar dispatch above before
708                // this fallback, so this active path receives RGB-family
709                // representations and applies the RGB inverse directly.
710                DynamicImage::ImageRgba8(crate::color::rgb_to_cmyk_inverse(&converted.to_rgb8()))
711            } else if mode == "L" || mode == "LA" {
712                if mode == "L" && src_mode == "YCbCr" {
713                    // Pillow's C converter maps YCbCr to L through the Y
714                    // band directly, not through the RGB luma.
715                    DynamicImage::ImageLuma8(ycbcr_luma8(img))
716                } else if mode == "LA" && src_mode == "YCbCr" {
717                    // Convert.c's ycbcr2la likewise copies the Y band and
718                    // installs an opaque alpha byte. Reconstructing RGB
719                    // first would change the fixed-point Y value and expose
720                    // a storage byte as alpha.
721                    let gray = ycbcr_luma8(img);
722                    let (width, height) = gray.dimensions();
723                    let mut la = crate::raster::GrayAlphaImage::new(width, height);
724                    for (output, gray_pixel) in la.pixels_mut().zip(gray.pixels()) {
725                        output[0] = gray_pixel[0];
726                        output[1] = 255;
727                    }
728                    DynamicImage::ImageLumaA8(la)
729                } else if mode == "L" {
730                    DynamicImage::ImageLuma8(color::pil_grayscale(&converted)?)
731                } else {
732                    let mut la = if src_mode == "PA" {
733                        // PA expansion carries the source alpha in the RGBA
734                        // result.  Keep that band when Pillow converts PA to
735                        // LA; the generic grayscale-alpha helper intentionally
736                        // creates an opaque alpha band for RGB-family inputs.
737                        let gray = color::pil_grayscale(&converted)?;
738                        let rgba = converted.to_rgba8();
739                        let (width, height) = gray.dimensions();
740                        let mut result = crate::raster::GrayAlphaImage::new(width, height);
741                        for ((output, gray_pixel), rgba_pixel) in
742                            result.pixels_mut().zip(gray.pixels()).zip(rgba.pixels())
743                        {
744                            output[0] = gray_pixel[0];
745                            output[1] = rgba_pixel[3];
746                        }
747                        result
748                    } else {
749                        color::pil_grayscale_alpha(&converted)?
750                    };
751                    if src_mode == "P" {
752                        // Pillow carries palette transparency into the LA
753                        // alpha band (putpalettealpha before converting).
754                        let indices = img.to_luma8();
755                        if let Some(table) = palette_alpha_for_convert(self) {
756                            for (op, ip) in la.pixels_mut().zip(indices.pixels()) {
757                                op[1] = table.get(usize::from(ip[0])).copied().unwrap_or(255);
758                            }
759                        }
760                    }
761                    DynamicImage::ImageLumaA8(la)
762                }
763            } else if mode == "RGB" {
764                // PA expansion carries the per-pixel alpha needed by RGBA
765                // conversion, but Pillow's RGB conversion drops that band.
766                DynamicImage::ImageRgb8(converted.into_rgb8())
767            } else if mode == "RGBA" {
768                // P sources with palette alpha keep per-entry alpha when
769                // converting to RGBA; the RGB-only nonstandard path would
770                // force every pixel opaque.
771                if src_mode == "P" {
772                    let palette_alpha = self.palette_alpha().unwrap_or_default();
773                    if !palette_alpha.is_empty() {
774                        let indices = img.to_luma8();
775                        let pal = palette.as_deref().unwrap_or_default();
776                        return Ok(Image::from_dynamic(
777                            crate::image::expand_palette(&indices, pal, &palette_alpha),
778                            explicit_mode_for(mode),
779                        ));
780                    }
781                }
782                // PA expansion already owns RGBA pixels. Consume that buffer
783                // instead of cloning the entire frame at the output boundary;
784                // other source variants keep DynamicImage's conversion path.
785                DynamicImage::ImageRgba8(converted.into_rgba8())
786            } else {
787                converted
788            };
789            if mode != "1" {
790                return Ok(Image::from_dynamic(result, explicit_mode_for(mode)));
791            }
792            // Binary mode "1" falls through to the shared threshold/dither
793            // path below, which re-derives the grayscale from the
794            // non-standard source and applies Pillow's dither policy.
795        }
796
797        let dither_enum = parse_dither(dither)?;
798
799        // Special case: converting to binary mode "1" — must eagerly execute
800        // because the pipeline's scalar::convert doesn't handle binary threshold/dither.
801        if mode == "1" {
802            if effective_src_mode == "CMYK" && matches!(dither_enum, Some(DitherMethod::None)) {
803                // This conversion only reads source pixels. Borrow the cached
804                // materialization so we do not clone the full CMYK frame.
805                let img = self.materialized_shared()?;
806                let out = crate::color::cmyk_to_binary_truncate(img.as_ref())?;
807                return Ok(Image::from_dynamic(
808                    DynamicImage::ImageLuma8(out),
809                    Some("1".to_string()),
810                ));
811            }
812            let img = self.materialize()?;
813            // Use truncated grayscale (PIL uses integer truncation, not rounding)
814            let gray = if effective_src_mode == "CMYK" {
815                crate::color::cmyk_to_grayscale_truncate(&img)?
816            } else if is_nonstandard_mode(&effective_src_mode) {
817                let palette = self.palette();
818                let rgb = crate::color::convert_from_nonstandard(
819                    &effective_src_mode,
820                    &img,
821                    palette.as_deref(),
822                )
823                .unwrap_or_else(|| img.to_rgb8().into());
824                crate::color::pil_grayscale_truncate(&rgb)?
825            } else {
826                crate::color::pil_grayscale_truncate(&img)?
827            };
828            let (w, h) = gray.dimensions();
829            let mut out = crate::raster::GrayImage::new(w, h);
830            // Pillow's indexed conversion path thresholds P/PA palette colors
831            // directly for mode "1", even when Floyd-Steinberg is requested
832            // or implied by the default. Do not dither after expanding them.
833            let use_threshold = matches!(dither_enum, Some(DitherMethod::None))
834                || matches!(effective_src_mode.as_str(), "P" | "PA");
835            if use_threshold {
836                // Threshold at 128 (PIL: pixel >= 128 -> 255, else 0)
837                for (op, gp) in out.pixels_mut().zip(gray.pixels()) {
838                    op[0] = if gp[0] >= 128 { 255 } else { 0 };
839                }
840            } else {
841                // Floyd-Steinberg dither (PIL's tobilevel with error diffusion)
842                // Uses PIL's exact error propagation pattern (scaled by 16).
843                // Key detail: after the inner loop, PIL writes errors[w] = l0
844                // so the next row's last pixel reads the down/down-right error
845                // from this row's last pixel.
846                // For RGB source, compute luminance inline using PIL's formula
847                // (299*R + 587*G + 114*B) / 1000 to exactly match PIL behavior.
848                // The pre-computed grayscale uses >> 16 which differs for 5 out
849                // of 16M RGB values.
850                // Non-standard sources (HSV/YCbCr) are stored in RGB
851                // containers but their byte values are not RGB; their
852                // true luminance is in the pre-computed `gray`.
853                let source_is_nonstandard = is_nonstandard_mode(&effective_src_mode);
854                let is_rgb =
855                    matches!(img.color(), crate::raster::ColorType::Rgb8) && !source_is_nonstandard;
856                let mut errors = vec![0i32; (w + 1) as usize];
857                let wu = w as usize;
858                if is_rgb {
859                    let rgb = img.to_rgb8();
860                    let rgb_raw = rgb.into_raw();
861                    for y in 0..h as usize {
862                        let mut l = 0i32;
863                        let mut l0: i32 = 0;
864                        let mut l1: i32 = 0;
865                        let row_base = y * wu * 3;
866                        for x in 0..wu {
867                            let r = rgb_raw[row_base + x * 3] as i32;
868                            let g = rgb_raw[row_base + x * 3 + 1] as i32;
869                            let b = rgb_raw[row_base + x * 3 + 2] as i32;
870                            let lum = (299 * r + 587 * g + 114 * b) / 1000;
871                            let acc = l + errors[x + 1];
872                            let v = (lum + acc / 16).clamp(0, 255);
873                            let new = if v > 128 { 255i32 } else { 0i32 };
874                            out.get_pixel_mut(x as u32, y as u32)[0] = new as u8;
875                            l = v - new;
876                            let l2 = l;
877                            let d2 = l + l;
878                            l += d2;
879                            errors[x] = l + l0;
880                            l += d2;
881                            l0 = l + l1;
882                            l1 = l2;
883                            l += d2;
884                        }
885                        errors[wu] = l0;
886                    }
887                } else {
888                    let src: Vec<i32> = gray.pixels().map(|p| p[0] as i32).collect();
889                    for y in 0..h as usize {
890                        let mut l = 0i32;
891                        let mut l0: i32 = 0;
892                        let mut l1: i32 = 0;
893                        for x in 0..wu {
894                            let idx = y * wu + x;
895                            let acc = l + errors[x + 1];
896                            let v = src[idx] + acc / 16;
897                            let v = v.clamp(0, 255);
898                            let new = if v > 128 { 255i32 } else { 0i32 };
899                            out.get_pixel_mut(x as u32, y as u32)[0] = new as u8;
900                            l = v - new;
901                            let l2 = l;
902                            let d2 = l + l;
903                            l += d2;
904                            errors[x] = l + l0;
905                            l += d2;
906                            l0 = l + l1;
907                            l1 = l2;
908                            l += d2;
909                        }
910                        errors[wu] = l0;
911                    }
912                }
913            }
914            return Ok(Image::from_dynamic(
915                DynamicImage::ImageLuma8(out),
916                Some("1".to_string()),
917            ));
918        }
919
920        // Special case: converting to P-mode uses PIL's default WEB palette
921        // with Floyd-Steinberg dither, not median cut quantize. We eagerly execute
922        // here so the palette is stored on the result Pipeline, enabling subsequent
923        // convert("RGB") operations to do correct palette lookups.
924        if mode == "P" {
925            if src_mode == "RGBA" {
926                // Pillow routes RGBA->P through FASTOCTREE rather than the
927                // fixed WEB palette used for RGB-family sources without an
928                // alpha band.  Returning the quantizer's indexed pipeline
929                // also preserves its palette metadata for later conversions.
930                return self.quantize(256, 0, None, true, 2);
931            }
932            use crate::ops::quantize::web_palette_quantize;
933            use std::sync::Arc;
934
935            let img = self.materialize()?;
936            let (w, h) = (img.width(), img.height());
937            let (indices, palette_bytes) = if matches!(src_mode.as_str(), "1" | "L" | "LA") {
938                // Pillow 12.2 Convert.c maps L/1 samples directly to P indices
939                // and installs the identity grayscale palette. LA uses the
940                // same luma-band path; its alpha is not part of a P result.
941                // Web quantization would change the indices before mixed-mode
942                // paste/composite.
943                let indices = img.to_luma8().into_raw();
944                let palette = (0u8..=u8::MAX)
945                    .flat_map(|value| [value, value, value])
946                    .collect();
947                (indices, palette)
948            } else {
949                let rgb = img.to_rgb8();
950                let rgb_raw = rgb.into_raw();
951                let dither = !matches!(dither_enum, Some(DitherMethod::None));
952                web_palette_quantize(&rgb_raw, w, h, dither)?
953            };
954            let mut out = crate::raster::GrayImage::new(w, h);
955            for (i, pixel) in out.pixels_mut().enumerate() {
956                pixel[0] = indices.get(i).copied().unwrap_or(0);
957            }
958            // Pillow retains the source EXIF record across mode conversion;
959            // this matters when a converted indexed image is subsequently
960            // passed to ImageOps.exif_transpose. Keep the encoded metadata on
961            // the pipeline source so the public operation can remove the
962            // orientation tag after transposing the palette indices.
963            let source = crate::image::LoadedData {
964                image: Arc::new(DynamicImage::ImageLuma8(out)),
965                known_zero_fill: false,
966                explicit_mode: Some("P".to_string()),
967                decoded_mode: crate::raster::ColorType::L8.into(),
968                palette: None,
969                palette_alpha: None,
970                source_format: self.source_format(),
971                info: self.image_info(),
972                exif: self.exif_metadata(),
973            };
974            return Ok(Image::Pipeline {
975                source: Arc::new(Image::Loaded(source)),
976                ops: PipelineOps::empty(),
977                format: None,
978                explicit_mode: Some("P".to_string()),
979                backend: None,
980                palette: Some(palette_bytes),
981                palette_alpha: None,
982                materialized: crate::image::materialization_cache(),
983                shape: crate::image::pipeline_shape_cache(),
984                mode: crate::image::pipeline_mode_cache(),
985            });
986        }
987
988        // I/F targets keep their four-byte sample representation. Unlike
989        // ordinary RGB-backed conversions, a CMYK source must first expand
990        // C/M/Y/K into RGB; the deferred Convert op only receives the target
991        // mode tag, so preserve this source-specific conversion here.
992        if effective_src_mode_name == "CMYK" && matches!(mode, "I" | "F") {
993            let img = self.materialize()?;
994            let rgb = crate::color::cmyk_to_rgb(&img).to_rgb8();
995            let (w, h) = rgb.dimensions();
996            let mut out = crate::raster::RgbaImage::new(w, h);
997            for (output, pixel) in out.pixels_mut().zip(rgb.pixels()) {
998                let r = i32::from(pixel[0]);
999                let g = i32::from(pixel[1]);
1000                let b = i32::from(pixel[2]);
1001                if mode == "I" {
1002                    let value = (19595i32 * r + 38470i32 * g + 7471i32 * b + 32768) >> 16;
1003                    *output = crate::raster::Rgba(value.to_le_bytes());
1004                } else {
1005                    let value = (r * 299 + g * 587 + b * 114) as f32 / 1000.0;
1006                    *output = crate::raster::Rgba(value.to_le_bytes());
1007                }
1008            }
1009            let result = crate::raster::DynamicImage::ImageRgba8(out);
1010            return Ok(Image::from_dynamic(result, explicit_mode_for(mode)));
1011        }
1012
1013        let mode_enum = parse_mode(mode)?;
1014        if src_mode == "RGB" && mode == "L" {
1015            // RGB→L and ImageOps.grayscale share Pillow's exact fixed-point
1016            // luma contract. Reuse its native-layout executor so SIMD can
1017            // use the packed RGB kernel and GPU can upload RGB/read back L
1018            // without passing the conversion through an RGBA carrier.
1019            return Ok(Image::push_op(self, PipelineOp::Grayscale));
1020        }
1021        // Pillow accepts a dither argument on convert(), but its standard
1022        // byte-mode converters do not consume it. Keep the descriptor free of
1023        // a phantom default Floyd-Steinberg value so the GPU contract can
1024        // dispatch the exact byte-to-byte kernel. Binary and palette targets
1025        // still retain the normalized dither because their conversion paths
1026        // use it above.
1027        let pipeline_dither = if matches!(mode, "P" | "1") {
1028            dither_enum
1029        } else {
1030            // Pillow's byte and scalar converters do not consume the dither
1031            // enum. Keeping the default Floyd-Steinberg value on CMYK/HSV/
1032            // YCbCr/I/F descriptors needlessly blocks their exact GPU byte
1033            // kernels and does not describe an operation the converter uses.
1034            None
1035        };
1036        let mut result = Image::push_op(
1037            self,
1038            PipelineOp::Convert {
1039                mode: mode_enum,
1040                matrix: None,
1041                dither: pipeline_dither,
1042            },
1043        );
1044        // Set explicit_mode on the pipeline for non-standard modes
1045        if let Some(em) = explicit_mode_for(mode) {
1046            if let Image::Pipeline {
1047                explicit_mode: em_field,
1048                ..
1049            } = &mut result
1050            {
1051                *em_field = Some(em.to_string());
1052            }
1053        }
1054        Ok(result)
1055    }
1056}
1057
1058/// Convert a source image to Pillow's palette-plus-alpha representation.
1059///
1060/// Pillow's `Convert.c` treats `PA` as an indexed destination, not as a
1061/// spelling of `LA`: RGB-family and CMYK/HSV/YCbCr sources are mapped through
1062/// the default WEB palette, RGBA keeps the source alpha bytes, and scalar or
1063/// indexed sources retain their byte/index values. Scalar sources also receive
1064/// Pillow's identity grayscale palette, so a later `PA` expansion resolves an
1065/// index back to the original scalar value. Keeping those paths explicit also
1066/// avoids feeding `PA` into the ordinary scalar pipeline, which has no palette
1067/// storage to attach to its result.
1068fn identity_grayscale_palette() -> Vec<u8> {
1069    (0u8..=u8::MAX)
1070        .flat_map(|value| [value, value, value])
1071        .collect()
1072}
1073
1074/// Splits RGBA bytes for Pillow's RGBA-to-PA conversion without widening or
1075/// copying an already materialized RGBA source.  Pillow quantizes RGB only,
1076/// then carries the original alpha bytes into the PA result.
1077fn split_rgba_for_palette(
1078    source: &DynamicImage,
1079) -> Result<(crate::raster::RgbImage, Vec<u8>), PilError> {
1080    let rgba: Cow<'_, crate::raster::RgbaImage> = match source {
1081        DynamicImage::ImageRgba8(rgba) => Cow::Borrowed(rgba),
1082        other => Cow::Owned(other.to_rgba8()),
1083    };
1084    let width = rgba.width();
1085    let height = rgba.height();
1086    let pixel_count = (width as usize)
1087        .checked_mul(height as usize)
1088        .ok_or_else(|| PilError::ValueError("palette conversion failed".to_owned()))?;
1089    let rgb_len = pixel_count
1090        .checked_mul(3)
1091        .ok_or_else(|| PilError::ValueError("palette conversion failed".to_owned()))?;
1092    let rgba_len = pixel_count
1093        .checked_mul(4)
1094        .ok_or_else(|| PilError::ValueError("palette conversion failed".to_owned()))?;
1095    let input = rgba
1096        .as_raw()
1097        .get(..rgba_len)
1098        .ok_or_else(|| PilError::ValueError("palette conversion failed".to_owned()))?;
1099    let mut rgb = Vec::with_capacity(rgb_len);
1100    let mut alpha = Vec::with_capacity(pixel_count);
1101    for pixel in input.chunks_exact(4) {
1102        rgb.extend_from_slice(&pixel[..3]);
1103        alpha.push(pixel[3]);
1104    }
1105    let rgb = crate::raster::RgbImage::from_raw(width, height, rgb)
1106        .ok_or_else(|| PilError::ValueError("palette conversion failed".to_owned()))?;
1107    Ok((rgb, alpha))
1108}
1109
1110fn convert_to_palette_alpha(
1111    image: &Image,
1112    source_mode: &str,
1113    dither: Option<DitherMethod>,
1114) -> Result<Image, PilError> {
1115    // Keep shared source storage for read-only conversions while preserving
1116    // the logical-mode validation performed by Image::materialize().
1117    let source = image.materialized_shared_for_ops()?;
1118    let (indices, palette, alpha) = match source_mode {
1119        "P" => {
1120            let indices = source.to_luma8();
1121            let table = palette_alpha_for_convert(image);
1122            let alpha = indices
1123                .pixels()
1124                .map(|pixel| {
1125                    table
1126                        .as_ref()
1127                        .and_then(|values| values.get(usize::from(pixel[0])))
1128                        .copied()
1129                        .unwrap_or(255)
1130                })
1131                .collect();
1132            (indices, image.palette(), alpha)
1133        }
1134        "1" | "L" | "LA" => {
1135            let indices = source.to_luma8();
1136            let alpha = vec![255; indices.width() as usize * indices.height() as usize];
1137            (indices, Some(identity_grayscale_palette()), alpha)
1138        }
1139        "I" => {
1140            // I->P is a direct clamped scalar-to-index conversion.  The
1141            // intermediate RGB helper preserves that value without applying
1142            // the I->L scaling formula used by ordinary grayscale conversion.
1143            let indices = color::i_to_rgb(&source).to_luma8();
1144            let alpha = vec![255; indices.width() as usize * indices.height() as usize];
1145            (indices, Some(identity_grayscale_palette()), alpha)
1146        }
1147        "F" => {
1148            // F->P truncates the clamped float value to an index, matching the
1149            // existing F->RGB helper because all three broadcast channels are
1150            // identical.
1151            let indices = color::f_to_rgb(&source).to_luma8();
1152            let alpha = vec![255; indices.width() as usize * indices.height() as usize];
1153            (indices, Some(identity_grayscale_palette()), alpha)
1154        }
1155        "RGBA" => {
1156            // Pillow's Python conversion splits RGBA into RGB and alpha,
1157            // quantizes only the RGB image, then merges the original alpha
1158            // band into PA.  Quantizing RGBA and moving transparent entries
1159            // afterward produces different palette-index order for valid
1160            // images with distinct transparent and visible colors.
1161            let (rgb, alpha) = split_rgba_for_palette(source.as_ref())?;
1162            let (width, height) = rgb.dimensions();
1163            let quantized =
1164                Image::from_dynamic(DynamicImage::ImageRgb8(rgb), Some("RGB".to_owned()))
1165                    // Image.convert("PA") calls RGB.quantize() without a method;
1166                    // RGB therefore uses MEDIANCUT (method 0), not RGBA's FASTOCTREE
1167                    // default.  The palette-index order is observable in PA bytes.
1168                    .quantize(256, 0, None, true, 0)?;
1169            let index_bytes = quantized.materialize()?.to_luma8().into_raw();
1170            let palette = quantized.palette();
1171            let indices = crate::raster::GrayImage::from_raw(width, height, index_bytes)
1172                .ok_or_else(|| PilError::ValueError("palette conversion failed".to_owned()))?;
1173            (indices, palette, alpha)
1174        }
1175        "CMYK" | "HSV" | "YCbCr" => {
1176            let source_palette = image.palette();
1177            let rgb =
1178                color::convert_from_nonstandard(source_mode, &source, source_palette.as_deref())
1179                    .unwrap_or_else(|| source.to_rgb8().into())
1180                    .to_rgb8();
1181            let (width, height) = rgb.dimensions();
1182            let dither = !matches!(dither, Some(DitherMethod::None));
1183            let (indices, palette) = crate::ops::quantize::web_palette_quantize(
1184                &rgb.clone().into_raw(),
1185                width,
1186                height,
1187                dither,
1188            )?;
1189            let indices = crate::raster::GrayImage::from_raw(width, height, indices)
1190                .ok_or_else(|| PilError::ValueError("palette conversion failed".to_owned()))?;
1191            let alpha = vec![255; width as usize * height as usize];
1192            (indices, Some(palette), alpha)
1193        }
1194        _ => {
1195            let rgb = source.to_rgb8();
1196            let (width, height) = rgb.dimensions();
1197            let dither = !matches!(dither, Some(DitherMethod::None));
1198            let (indices, palette) = crate::ops::quantize::web_palette_quantize(
1199                &rgb.clone().into_raw(),
1200                width,
1201                height,
1202                dither,
1203            )?;
1204            let indices = crate::raster::GrayImage::from_raw(width, height, indices)
1205                .ok_or_else(|| PilError::ValueError("palette conversion failed".to_owned()))?;
1206            let alpha = vec![255; width as usize * height as usize];
1207            (indices, Some(palette), alpha)
1208        }
1209    };
1210
1211    let (width, height) = indices.dimensions();
1212    let index_bytes = indices.into_raw();
1213    let mut pa = crate::raster::GrayAlphaImage::new(width, height);
1214    for (position, output) in pa.pixels_mut().enumerate() {
1215        output[0] = index_bytes[position];
1216        output[1] = alpha.get(position).copied().unwrap_or(255);
1217    }
1218
1219    Ok(Image::Loaded(crate::image::LoadedData {
1220        image: std::sync::Arc::new(DynamicImage::ImageLumaA8(pa)),
1221        known_zero_fill: false,
1222        explicit_mode: Some("PA".to_owned()),
1223        decoded_mode: crate::raster::ColorType::La8.into(),
1224        palette,
1225        palette_alpha: None,
1226        // Pillow's mode conversion returns a detached image and does not
1227        // carry the source decoder format or transient info dictionary into
1228        // the result.  Retain only EXIF, matching the existing P/PA path.
1229        source_format: None,
1230        info: None,
1231        exif: image.exif_metadata(),
1232    }))
1233}
1234
1235fn explicit_mode_for(mode: &str) -> Option<String> {
1236    match mode {
1237        "1" | "P" | "CMYK" | "HSV" | "YCbCr" | "I" | "F" | "LAB" => Some(mode.to_string()),
1238        _ => None,
1239    }
1240}
1241
1242fn convert_with_matrix(
1243    img: &crate::raster::DynamicImage,
1244    target_mode: &str,
1245    matrix: &[f64],
1246) -> Result<crate::raster::DynamicImage, PilError> {
1247    #[inline]
1248    fn round_clip(value: f64) -> u8 {
1249        value.round().clamp(0.0, 255.0) as u8
1250    }
1251
1252    match (matrix.len(), target_mode) {
1253        (4, "RGB") => {
1254            // Pillow 12.2 retains a legacy four-coefficient RGB-output path:
1255            // the affine expression is written to the first channel and the
1256            // other channels are zero for the deterministic public fixture.
1257            let rgb = img.to_rgb8();
1258            let (w, h) = rgb.dimensions();
1259            let pixels: Vec<u8> = rgb
1260                .pixels()
1261                .flat_map(|p| {
1262                    [
1263                        round_clip(
1264                            matrix[0] * p[0] as f64
1265                                + matrix[1] * p[1] as f64
1266                                + matrix[2] * p[2] as f64
1267                                + matrix[3],
1268                        ),
1269                        0,
1270                        0,
1271                    ]
1272                })
1273                .collect();
1274            Ok(crate::raster::DynamicImage::ImageRgb8(
1275                crate::raster::RgbImage::from_raw(w, h, pixels)
1276                    .ok_or_else(|| PilError::ValueError("matrix conversion failed".into()))?,
1277            ))
1278        }
1279        (4, "L") => {
1280            // Pillow's four-coefficient matrix path applies one affine
1281            // expression to the RGB source and produces a luma image.
1282            let rgb = img.to_rgb8();
1283            let (w, h) = rgb.dimensions();
1284            let pixels: Vec<u8> = rgb
1285                .pixels()
1286                .map(|p| {
1287                    round_clip(
1288                        matrix[0] * p[0] as f64
1289                            + matrix[1] * p[1] as f64
1290                            + matrix[2] * p[2] as f64
1291                            + matrix[3],
1292                    )
1293                })
1294                .collect();
1295            Ok(crate::raster::DynamicImage::ImageLuma8(
1296                crate::raster::GrayImage::from_raw(w, h, pixels)
1297                    .ok_or_else(|| PilError::ValueError("matrix conversion failed".into()))?,
1298            ))
1299        }
1300        (12, "RGB") => {
1301            let rgb = img.to_rgb8();
1302            let (w, h) = rgb.dimensions();
1303            let pixels: Vec<u8> = rgb
1304                .pixels()
1305                .flat_map(|p| {
1306                    let r = p[0] as f64;
1307                    let g = p[1] as f64;
1308                    let b = p[2] as f64;
1309                    [
1310                        round_clip(matrix[0] * r + matrix[1] * g + matrix[2] * b + matrix[3]),
1311                        round_clip(matrix[4] * r + matrix[5] * g + matrix[6] * b + matrix[7]),
1312                        round_clip(matrix[8] * r + matrix[9] * g + matrix[10] * b + matrix[11]),
1313                    ]
1314                })
1315                .collect();
1316            Ok(crate::raster::DynamicImage::ImageRgb8(
1317                crate::raster::RgbImage::from_raw(w, h, pixels)
1318                    .ok_or_else(|| PilError::ValueError("matrix conversion failed".into()))?,
1319            ))
1320        }
1321        (n, _) => Err(PilError::ValueError(format!(
1322            "Matrix must be 4 or 12 elements, got {}",
1323            n
1324        ))),
1325    }
1326}
1327
1328#[cfg(test)]
1329mod tests {
1330    use crate::image::Image;
1331    use crate::ops::paste::PasteSource;
1332
1333    #[test]
1334    fn rgba_palette_split_preserves_rgb_and_alpha_bytes() {
1335        let source = crate::raster::DynamicImage::ImageRgba8(
1336            crate::raster::RgbaImage::from_raw(2, 1, vec![10, 20, 30, 40, 50, 60, 70, 80])
1337                .expect("valid RGBA source"),
1338        );
1339
1340        let (rgb, alpha) =
1341            super::split_rgba_for_palette(&source).expect("split RGBA palette source");
1342        assert_eq!(rgb.into_raw(), [10, 20, 30, 50, 60, 70]);
1343        assert_eq!(alpha, [40, 80]);
1344    }
1345
1346    #[test]
1347    fn rgba_palette_split_ignores_trailing_storage() {
1348        let source = crate::raster::DynamicImage::ImageRgba8(
1349            crate::raster::RgbaImage::from_raw(1, 1, vec![10, 20, 30, 40, 50, 60, 70, 80])
1350                .expect("valid RGBA source with trailing storage"),
1351        );
1352
1353        let (rgb, alpha) =
1354            super::split_rgba_for_palette(&source).expect("split logical RGBA pixels");
1355        assert_eq!(rgb.into_raw(), [10, 20, 30]);
1356        assert_eq!(alpha, [40]);
1357    }
1358
1359    #[test]
1360    fn integer_to_rgb_clamps_native_i_samples_and_broadcasts_them() {
1361        let samples = [-1_i32, 0, 1, 127, 255, 256, i32::MIN, i32::MAX];
1362        let source_bytes: Vec<u8> = samples
1363            .iter()
1364            .flat_map(|value| value.to_le_bytes())
1365            .collect();
1366        let source = Image::from_dynamic(
1367            crate::raster::DynamicImage::ImageRgba8(
1368                crate::raster::RgbaImage::from_raw(samples.len() as u32, 1, source_bytes)
1369                    .expect("valid I-mode carrier"),
1370            ),
1371            Some("I".to_owned()),
1372        );
1373
1374        let converted = source
1375            .convert("RGB", None, None, None, None)
1376            .expect("I to RGB conversion");
1377
1378        assert_eq!(converted.mode().expect("converted mode"), "RGB");
1379        assert_eq!(
1380            converted.tobytes().expect("converted bytes"),
1381            [
1382                0, 0, 0, 0, 0, 0, 1, 1, 1, 127, 127, 127, 255, 255, 255, 255, 255, 255, 0, 0, 0,
1383                255, 255, 255,
1384            ]
1385        );
1386    }
1387
1388    #[test]
1389    fn float_to_rgb_clamps_and_truncates_native_f_samples() {
1390        let samples = [-1.5_f32, 0.0, 0.9, 1.9, 127.9, 255.9, 256.5];
1391        let source_bytes: Vec<u8> = samples
1392            .iter()
1393            .flat_map(|value| value.to_le_bytes())
1394            .collect();
1395        let source = Image::from_dynamic(
1396            crate::raster::DynamicImage::ImageRgba8(
1397                crate::raster::RgbaImage::from_raw(samples.len() as u32, 1, source_bytes)
1398                    .expect("valid F-mode carrier"),
1399            ),
1400            Some("F".to_owned()),
1401        );
1402
1403        let converted = source
1404            .convert("RGB", None, None, None, None)
1405            .expect("F to RGB conversion");
1406
1407        assert_eq!(converted.mode().expect("converted mode"), "RGB");
1408        assert_eq!(
1409            converted.tobytes().expect("converted bytes"),
1410            [
1411                0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 127, 127, 127, 255, 255, 255, 255, 255, 255,
1412            ]
1413        );
1414    }
1415
1416    #[test]
1417    fn luma8_to_luma16_conversion_and_paste_preserve_numeric_sample() {
1418        for mode in ["I;16", "I;16L", "I;16B", "I;16N"] {
1419            let source = Image::new(1, 1, "L", (17, 17, 17, 255)).expect("source image");
1420            let converted = source
1421                .convert(mode, None, None, None, None)
1422                .expect("I;16 conversion");
1423            assert_eq!(converted.mode().expect("converted mode"), mode);
1424            assert_eq!(
1425                converted.tobytes().expect("converted bytes"),
1426                match mode {
1427                    "I;16B" => vec![0, 17],
1428                    _ => vec![17, 0],
1429                }
1430            );
1431
1432            let mut destination =
1433                Image::new(1, 1, mode, (0, 0, 0, 255)).expect("destination image");
1434            destination
1435                .paste(
1436                    PasteSource::Image(Box::new(source)),
1437                    Some((0, 0, 1, 1)),
1438                    None,
1439                )
1440                .expect("I;16 paste");
1441            assert_eq!(
1442                destination.tobytes().expect("pasted bytes"),
1443                match mode {
1444                    "I;16B" => vec![0, 17],
1445                    _ => vec![17, 0],
1446                }
1447            );
1448        }
1449    }
1450}