Skip to main content

pillow_rs/ops/
paste.rs

1//! Paste operations — image overlay, color fill, and mask-based alpha blending.
2
3use std::sync::Arc;
4
5use crate::checked_dims::CheckedDims;
6use crate::error::PilError;
7use crate::image::Image;
8use crate::ops::crop::check_crop_extent;
9use crate::pipeline::PipelineOp;
10
11fn coordinate_overflow() -> PilError {
12    PilError::OverflowError("signed integer is greater than maximum".into())
13}
14
15/// Source pixels for [`Image::paste`].
16#[derive(Debug, Clone)]
17pub enum PasteSource {
18    /// Paste pixels from another image.
19    Image(Box<Image>),
20    /// Paste a scalar pixel value.
21    Scalar(u8),
22    /// Paste a two-band luma/alpha pixel value.
23    LumaAlpha(u8, u8),
24    /// Paste a three-band pixel value.
25    Rgb(u8, u8, u8),
26    /// Paste a four-band pixel value.
27    Rgba(u8, u8, u8, u8),
28    /// Paste a Python integer before mode-specific Pillow coercion.
29    RawScalar(i64),
30    /// Paste a Python floating-point scalar in an `F` destination.
31    RawFloat(f64),
32    /// Paste a Python two-component tuple before component clipping.
33    RawLumaAlpha(i64, i64),
34    /// Paste a Python three-component tuple before component clipping.
35    RawRgb(i64, i64, i64),
36    /// Paste a Python four-component tuple before component clipping.
37    RawRgba(i64, i64, i64, i64),
38}
39
40/// Host-neutral source input for the Python `Image.paste` wrapper.
41#[derive(Debug, Clone)]
42pub enum PythonPasteSource {
43    /// Another image object.
44    Image(Box<Image>),
45    /// A scalar color value before mode-specific validation.
46    Scalar(i64),
47    /// A floating-point scalar, accepted by Pillow for `F` images.
48    Float(f64),
49    /// A tuple/list color before mode-specific arity validation.
50    Components(Vec<i64>),
51    /// A Pillow color string before mode-specific conversion.
52    String(String),
53    /// A value that is neither an image nor a supported color value.
54    Invalid,
55}
56
57/// Host-neutral box input for the Python `Image.paste` wrapper.
58#[derive(Debug, Clone)]
59pub enum PythonPasteBox {
60    /// No second argument was supplied.
61    None,
62    /// The abbreviated `(image, mask)` form.
63    Image(Box<Image>),
64    /// A coordinate list/tuple.
65    Values(Vec<i64>),
66    /// A value that could not be interpreted as a coordinate sequence.
67    Invalid {
68        /// The sequence length when the host object exposed one.
69        length: Option<usize>,
70        /// The host type name for objects without a length.
71        type_name: String,
72    },
73}
74
75/// Host-neutral mask input for the Python `Image.paste` wrapper.
76#[derive(Debug, Clone)]
77pub enum PythonPasteMask {
78    /// No mask was supplied.
79    None,
80    /// An image mask.
81    Image(Box<Image>),
82    /// A non-image object.
83    Invalid(String),
84}
85
86/// Host-neutral coordinate input for public `Image.alpha_composite` calls.
87#[derive(Debug, Clone)]
88pub enum AlphaCompositeBox {
89    /// A Python list/tuple represented as integer coordinates.
90    Values(Vec<i64>),
91    /// A value that was not an integer coordinate sequence.
92    Invalid,
93}
94
95impl PasteSource {
96    /// Builds a paste source from binding-normalized values.
97    ///
98    /// When `image` is present it takes priority. Otherwise the RGBA tuple is
99    /// used as a solid color source.
100    pub fn from_parts(image: Option<Image>, r: u8, g: u8, b: u8, a: u8) -> Self {
101        if let Some(img) = image {
102            PasteSource::Image(Box::new(img))
103        } else {
104            PasteSource::Rgba(r, g, b, a)
105        }
106    }
107
108    fn solid_color(&self, mode: &str) -> Result<ResolvedPasteColor, PilError> {
109        let bad_single =
110            || PilError::TypeError("color must be int or single-element tuple".to_owned());
111        let bad_la =
112            || PilError::TypeError("color must be int, or tuple of one or two elements".to_owned());
113        let bad_multi = || {
114            PilError::TypeError(
115                "color must be int, or tuple of one, three or four elements".to_owned(),
116            )
117        };
118
119        match (mode, self) {
120            ("1" | "L" | "P", PasteSource::Scalar(value)) => {
121                Ok(ResolvedPasteColor::Bytes((*value, *value, *value, 255)))
122            }
123            ("1" | "L" | "P", PasteSource::RawScalar(value)) => {
124                let value = clipped_byte(*value);
125                Ok(ResolvedPasteColor::Bytes((value, value, value, 255)))
126            }
127            ("1" | "L" | "P", _) => Err(bad_single()),
128            ("LA" | "PA", PasteSource::Scalar(value)) => {
129                Ok(ResolvedPasteColor::Bytes((*value, *value, *value, 0)))
130            }
131            ("LA" | "PA", PasteSource::RawScalar(value)) => {
132                let bytes = value.to_le_bytes();
133                Ok(ResolvedPasteColor::Bytes((
134                    bytes[0], bytes[0], bytes[0], bytes[3],
135                )))
136            }
137            ("LA" | "PA", PasteSource::LumaAlpha(luma, alpha)) => {
138                Ok(ResolvedPasteColor::Bytes((*luma, *luma, *luma, *alpha)))
139            }
140            ("LA" | "PA", PasteSource::RawLumaAlpha(luma, alpha)) => {
141                Ok(ResolvedPasteColor::Bytes((
142                    clipped_byte(*luma),
143                    clipped_byte(*luma),
144                    clipped_byte(*luma),
145                    clipped_byte(*alpha),
146                )))
147            }
148            ("LA" | "PA", _) => Err(bad_la()),
149            (
150                "RGB" | "RGBA" | "RGBa" | "RGBX" | "CMYK" | "YCbCr" | "HSV",
151                PasteSource::Scalar(value),
152            ) => Ok(ResolvedPasteColor::Bytes((*value, 0, 0, 0))),
153            ("RGB" | "YCbCr" | "HSV", PasteSource::RawScalar(value)) => {
154                let bytes = value.to_le_bytes();
155                Ok(ResolvedPasteColor::Bytes((
156                    bytes[0], bytes[1], bytes[2], 255,
157                )))
158            }
159            ("RGBA" | "RGBa" | "RGBX" | "CMYK", PasteSource::RawScalar(value)) => {
160                let bytes = value.to_le_bytes();
161                Ok(ResolvedPasteColor::Bytes((
162                    bytes[0], bytes[1], bytes[2], bytes[3],
163                )))
164            }
165            ("RGB" | "YCbCr" | "HSV", PasteSource::Rgb(r, g, b)) => {
166                Ok(ResolvedPasteColor::Bytes((*r, *g, *b, 255)))
167            }
168            ("RGB" | "YCbCr" | "HSV", PasteSource::RawRgb(r, g, b)) => {
169                Ok(ResolvedPasteColor::Bytes((
170                    clipped_byte(*r),
171                    clipped_byte(*g),
172                    clipped_byte(*b),
173                    255,
174                )))
175            }
176            ("RGB" | "YCbCr" | "HSV", PasteSource::Rgba(r, g, b, _)) => {
177                Ok(ResolvedPasteColor::Bytes((*r, *g, *b, 255)))
178            }
179            ("RGB" | "YCbCr" | "HSV", PasteSource::RawRgba(r, g, b, _)) => {
180                Ok(ResolvedPasteColor::Bytes((
181                    clipped_byte(*r),
182                    clipped_byte(*g),
183                    clipped_byte(*b),
184                    255,
185                )))
186            }
187            ("RGBA" | "RGBa" | "RGBX" | "CMYK", PasteSource::Rgb(r, g, b)) => {
188                Ok(ResolvedPasteColor::Bytes((*r, *g, *b, 255)))
189            }
190            ("RGBA" | "RGBa" | "RGBX" | "CMYK", PasteSource::RawRgb(r, g, b)) => {
191                Ok(ResolvedPasteColor::Bytes((
192                    clipped_byte(*r),
193                    clipped_byte(*g),
194                    clipped_byte(*b),
195                    255,
196                )))
197            }
198            ("RGBA" | "RGBa" | "RGBX" | "CMYK", PasteSource::Rgba(r, g, b, a)) => {
199                Ok(ResolvedPasteColor::Bytes((*r, *g, *b, *a)))
200            }
201            ("RGBA" | "RGBa" | "RGBX" | "CMYK", PasteSource::RawRgba(r, g, b, a)) => {
202                Ok(ResolvedPasteColor::Bytes((
203                    clipped_byte(*r),
204                    clipped_byte(*g),
205                    clipped_byte(*b),
206                    clipped_byte(*a),
207                )))
208            }
209            ("RGB" | "RGBA" | "RGBa" | "RGBX" | "CMYK" | "YCbCr" | "HSV", _) => Err(bad_multi()),
210            ("I", PasteSource::Scalar(value)) => Ok(ResolvedPasteColor::Integer(i32::from(*value))),
211            ("I", PasteSource::RawScalar(value)) => Ok(ResolvedPasteColor::Integer(
212                i32::try_from(*value)
213                    .map_err(|_| PilError::TypeError("im must be Image or color".to_owned()))?,
214            )),
215            ("F", PasteSource::Scalar(value)) => Ok(ResolvedPasteColor::Float(f32::from(*value))),
216            ("F", PasteSource::RawScalar(value)) => Ok(ResolvedPasteColor::Float(*value as f32)),
217            ("F", PasteSource::RawFloat(value)) => Ok(ResolvedPasteColor::Float(*value as f32)),
218            ("I", _) => Err(bad_single()),
219            // Pillow's ImagingPaste rejects tuple colors for F with the
220            // native real-number diagnostic, while I shares the ordinary
221            // integer/single-element tuple message.
222            ("F", _) => Err(PilError::TypeError(
223                "must be real number, not tuple".to_owned(),
224            )),
225            ("I;16" | "I;16L" | "I;16B" | "I;16N", PasteSource::Scalar(value)) => {
226                Ok(ResolvedPasteColor::Luma16(u16::from(*value) * 0x0101))
227            }
228            ("I;16" | "I;16L" | "I;16B" | "I;16N", _) => Err(bad_single()),
229            (_, _) => Err(PilError::ValueError(format!(
230                "unsupported paste destination mode {mode}"
231            ))),
232        }
233    }
234}
235
236#[derive(Debug, Clone, Copy)]
237enum ResolvedPasteColor {
238    Bytes((u8, u8, u8, u8)),
239    Integer(i32),
240    Float(f32),
241    Luma16(u16),
242}
243
244#[derive(Debug, Clone, Copy)]
245enum PastePlacement {
246    Position(i32, i32),
247    Region(i32, i32, i32, i32),
248}
249
250impl Image {
251    /// Applies the Python `Image.paste` input contract before queuing paste.
252    ///
253    /// Python and PyO3 bindings only classify host values into these neutral
254    /// records. Coordinate arity, abbreviated-box semantics, color arity,
255    /// mask errors, and the actual paste path all remain shared Rust logic.
256    pub fn paste_with_input(
257        &mut self,
258        source: PythonPasteSource,
259        box_input: PythonPasteBox,
260        mask_input: PythonPasteMask,
261    ) -> Result<(), PilError> {
262        let destination_mode = self.mode()?;
263        let source = match source {
264            PythonPasteSource::Image(image) => PasteSource::from_parts(Some(*image), 0, 0, 0, 255),
265            PythonPasteSource::Scalar(value) => paste_scalar_source(value, &destination_mode),
266            PythonPasteSource::Float(value) => PasteSource::RawFloat(value),
267            PythonPasteSource::Components(values) => match values.as_slice() {
268                [value] => paste_scalar_source(*value, &destination_mode),
269                [luma, alpha] => match (u8::try_from(*luma), u8::try_from(*alpha)) {
270                    (Ok(luma), Ok(alpha)) => PasteSource::LumaAlpha(luma, alpha),
271                    _ => PasteSource::RawLumaAlpha(*luma, *alpha),
272                },
273                [r, g, b] => match (u8::try_from(*r), u8::try_from(*g), u8::try_from(*b)) {
274                    (Ok(r), Ok(g), Ok(b)) => PasteSource::Rgb(r, g, b),
275                    _ => PasteSource::RawRgb(*r, *g, *b),
276                },
277                [r, g, b, a] => match (
278                    u8::try_from(*r),
279                    u8::try_from(*g),
280                    u8::try_from(*b),
281                    u8::try_from(*a),
282                ) {
283                    (Ok(r), Ok(g), Ok(b), Ok(a)) => PasteSource::from_parts(None, r, g, b, a),
284                    _ => PasteSource::RawRgba(*r, *g, *b, *a),
285                },
286                _ => return Err(invalid_component_error(&destination_mode)),
287            },
288            PythonPasteSource::String(value) => {
289                paste_source_from_color_string(&value, &destination_mode)?
290            }
291            PythonPasteSource::Invalid => {
292                return Err(invalid_component_error(&destination_mode));
293            }
294        };
295
296        let abbreviated_mask = match &box_input {
297            PythonPasteBox::Image(mask) => Some((**mask).clone()),
298            _ => None,
299        };
300        if abbreviated_mask.is_some() && !matches!(&mask_input, PythonPasteMask::None) {
301            return Err(PilError::ValueError(
302                "If using second argument as mask, third argument must be None".to_owned(),
303            ));
304        }
305        let mask = if let Some(image) = abbreviated_mask {
306            Some(image)
307        } else {
308            match mask_input {
309                PythonPasteMask::None => None,
310                PythonPasteMask::Image(image) => Some(*image),
311                PythonPasteMask::Invalid(type_name) => {
312                    return Err(PilError::AttributeError(format!(
313                        "'{type_name}' object has no attribute 'load'"
314                    )));
315                }
316            }
317        };
318
319        match box_input {
320            PythonPasteBox::None | PythonPasteBox::Image(_) => {
321                self.paste_at(source, None, mask.as_ref())
322            }
323            PythonPasteBox::Values(values) => match values.as_slice() {
324                [x, y] => {
325                    // Pillow rejects a two-coordinate solid-color paste for
326                    // lack of a region size before it validates the unused
327                    // coordinates. Keep that error ordering in core so a
328                    // huge coordinate does not change the public error.
329                    if !matches!(&source, PasteSource::Image(_)) && mask.is_none() {
330                        return self.paste_at(source, None, None);
331                    }
332                    self.paste_at(
333                        source,
334                        Some((coordinate(*x)?, coordinate(*y)?)),
335                        mask.as_ref(),
336                    )
337                }
338                [left, top, right, bottom] => self.paste(
339                    source,
340                    Some((
341                        coordinate(*left)?,
342                        coordinate(*top)?,
343                        coordinate(*right)?,
344                        coordinate(*bottom)?,
345                    )),
346                    mask.as_ref(),
347                ),
348                _ => Err(PilError::TypeError(format!(
349                    "argument 2 must be sequence of length 4, not {}",
350                    values.len()
351                ))),
352            },
353            PythonPasteBox::Invalid { length, type_name } => match length {
354                Some(length) => Err(PilError::TypeError(format!(
355                    "argument 2 must be sequence of length 4, not {length}"
356                ))),
357                None => Err(PilError::TypeError(format!(
358                    "object of type '{type_name}' has no len()"
359                ))),
360            },
361        }
362    }
363
364    /// Performs Pillow's high-level in-place alpha composite workflow.
365    ///
366    /// The low-level [`Image::alpha_composite`] primitive requires equal-sized
367    /// images. Pillow's public method first crops the source, crops or creates
368    /// the destination background, composites the matching regions, and pastes
369    /// the result back. Keeping that geometry here prevents Python/FFI copies
370    /// of the same validation and clipping rules.
371    pub fn alpha_composite_public(
372        &mut self,
373        source: &Image,
374        dest: AlphaCompositeBox,
375        source_box: AlphaCompositeBox,
376    ) -> Result<(), PilError> {
377        let source_box = match source_box {
378            AlphaCompositeBox::Values(values) if matches!(values.len(), 2 | 4) => values,
379            AlphaCompositeBox::Values(_) => {
380                return Err(PilError::ValueError(
381                    "Source must be a sequence of length 2 or 4".into(),
382                ));
383            }
384            AlphaCompositeBox::Invalid => {
385                return Err(PilError::ValueError(
386                    "Source must be a list or tuple".into(),
387                ));
388            }
389        };
390        let dest = match dest {
391            AlphaCompositeBox::Values(values) if values.len() == 2 => values,
392            AlphaCompositeBox::Values(_) => {
393                return Err(PilError::ValueError(
394                    "Destination must be a sequence of length 2".into(),
395                ));
396            }
397            AlphaCompositeBox::Invalid => {
398                return Err(PilError::ValueError(
399                    "Destination must be a list or tuple".into(),
400                ));
401            }
402        };
403        if source_box.iter().any(|value| *value < 0) {
404            return Err(PilError::ValueError("Source must be non-negative".into()));
405        }
406
407        let (source_width, source_height) = source.size()?;
408        let source_width = i64::try_from(source_width).map_err(|_| coordinate_overflow())?;
409        let source_height = i64::try_from(source_height).map_err(|_| coordinate_overflow())?;
410        let source_box = if source_box.len() == 2 {
411            [source_box[0], source_box[1], source_width, source_height]
412        } else {
413            [source_box[0], source_box[1], source_box[2], source_box[3]]
414        };
415        if source_box[2] < source_box[0] {
416            return Err(PilError::ValueError(
417                "Coordinate 'right' is less than 'left'".into(),
418            ));
419        }
420        if source_box[3] < source_box[1] {
421            return Err(PilError::ValueError(
422                "Coordinate 'lower' is less than 'upper'".into(),
423            ));
424        }
425        check_crop_extent(source_box[2] - source_box[0], source_box[3] - source_box[1])?;
426        let source_box = (
427            i32::try_from(source_box[0]).map_err(|_| coordinate_overflow())?,
428            i32::try_from(source_box[1]).map_err(|_| coordinate_overflow())?,
429            i32::try_from(source_box[2]).map_err(|_| coordinate_overflow())?,
430            i32::try_from(source_box[3]).map_err(|_| coordinate_overflow())?,
431        );
432        let overlay = if source_box == (0, 0, source_width as i32, source_height as i32) {
433            source.clone()
434        } else {
435            source.crop(Some(source_box))?
436        };
437
438        let dest_x = i32::try_from(dest[0]).map_err(|_| coordinate_overflow())?;
439        let dest_y = i32::try_from(dest[1]).map_err(|_| coordinate_overflow())?;
440        let (overlay_width, overlay_height) = overlay.size()?;
441        let right = dest_x
442            .checked_add(i32::try_from(overlay_width).map_err(|_| coordinate_overflow())?)
443            .ok_or_else(coordinate_overflow)?;
444        let bottom = dest_y
445            .checked_add(i32::try_from(overlay_height).map_err(|_| coordinate_overflow())?)
446            .ok_or_else(coordinate_overflow)?;
447        let box_coords = (dest_x, dest_y, right, bottom);
448        // Pillow's high-level method treats an empty cropped overlay as a
449        // no-op.  The low-level alpha compositor rejects zero-sized buffers
450        // as a mode/size mismatch, so avoid entering that primitive after the
451        // public geometry has already been validated.
452        if overlay_width == 0 || overlay_height == 0 {
453            return Ok(());
454        }
455        let destination_size = self.size()?;
456        if box_coords
457            == (
458                0,
459                0,
460                i32::try_from(destination_size.0).map_err(|_| coordinate_overflow())?,
461                i32::try_from(destination_size.1).map_err(|_| coordinate_overflow())?,
462            )
463        {
464            // A full-canvas unmasked paste would replace every output byte.
465            // After the same geometry/empty checks, queue only its composite;
466            // the low-level primitive retains mode and size validation. The
467            // immutable source graph still protects shared/copy-on-write data.
468            return self.alpha_composite(&overlay, (0, 0), (0, 0));
469        }
470        let background = self.crop(Some(box_coords))?;
471
472        let mut result = background.copy();
473        result.alpha_composite(&overlay, (0, 0), (0, 0))?;
474        self.paste(PasteSource::Image(Box::new(result)), Some(box_coords), None)
475    }
476
477    /// Queues a Pillow-style paste into this image.
478    ///
479    /// Image sources default to pasting at `(0, 0)` when `box_coords` is absent.
480    /// Color sources require a four-coordinate box so the fill region has a
481    /// defined width and height. `mask`, when present, is carried into the
482    /// pipeline for masked paste semantics.
483    ///
484    /// # Errors
485    ///
486    /// Returns [`PilError::ValueError`] when a color paste has no valid box.
487    /// Returns other [`PilError`] values when source size lookup or color-image
488    /// construction fails.
489    pub fn paste(
490        &mut self,
491        source: PasteSource,
492        box_coords: Option<(i32, i32, i32, i32)>,
493        mask: Option<&Image>,
494    ) -> Result<(), PilError> {
495        let placement = box_coords.map_or(PastePlacement::Position(0, 0), |coords| {
496            PastePlacement::Region(coords.0, coords.1, coords.2, coords.3)
497        });
498        self.paste_impl(source, placement, mask)
499    }
500
501    /// Queues a paste using Pillow's two-coordinate upper-left form.
502    ///
503    /// Image sources derive the region size from the source image. Solid values
504    /// derive it from `mask`, when supplied; without either size source Pillow
505    /// reports that a four-item box is required.
506    ///
507    /// # Errors
508    ///
509    /// Returns the same errors as [`Image::paste`].
510    pub fn paste_at(
511        &mut self,
512        source: PasteSource,
513        position: Option<(i32, i32)>,
514        mask: Option<&Image>,
515    ) -> Result<(), PilError> {
516        let (x, y) = position.unwrap_or((0, 0));
517        self.paste_impl(source, PastePlacement::Position(x, y), mask)
518    }
519
520    fn paste_impl(
521        &mut self,
522        source: PasteSource,
523        placement: PastePlacement,
524        mask: Option<&Image>,
525    ) -> Result<(), PilError> {
526        let destination_mode = self.mode()?;
527        let source_size = match &source {
528            PasteSource::Image(image) => Some(image.size()?),
529            _ => None,
530        };
531        let mask_size = mask.map(Image::size).transpose()?;
532        let (x, y, width, height) = match placement {
533            PastePlacement::Position(x, y) => {
534                let (width, height) = source_size.or(mask_size).ok_or_else(|| {
535                    PilError::ValueError("cannot determine region size; use 4-item box".to_owned())
536                })?;
537                (x, y, width, height)
538            }
539            PastePlacement::Region(left, top, right, bottom) => {
540                let raw_width = right
541                    .checked_sub(left)
542                    .and_then(|value| u32::try_from(value).ok());
543                let raw_height = bottom
544                    .checked_sub(top)
545                    .and_then(|value| u32::try_from(value).ok());
546                let degenerate = raw_width.map_or(true, |value| value == 0)
547                    || raw_height.map_or(true, |value| value == 0);
548                // Pillow Paste.c no-ops a solid-color fill whose box is
549                // degenerate (zero area or inverted edges); image pastes still
550                // raise the mismatch error.
551                if degenerate && !matches!(source, PasteSource::Image(_)) {
552                    return Ok(());
553                }
554                let width = raw_width
555                    .filter(|value| *value != 0)
556                    .ok_or_else(|| PilError::ValueError("images do not match".to_owned()))?;
557                let height = raw_height
558                    .filter(|value| *value != 0)
559                    .ok_or_else(|| PilError::ValueError("images do not match".to_owned()))?;
560                (left, top, width, height)
561            }
562        };
563
564        if source_size.is_some_and(|size| size != (width, height))
565            || mask_size.is_some_and(|size| size != (width, height))
566        {
567            return Err(PilError::ValueError("images do not match".to_owned()));
568        }
569
570        let mask_alpha = if let Some(mask_image) = mask {
571            match mask_image.mode()?.as_str() {
572                "1" | "L" => false,
573                "LA" | "RGBA" | "RGBa" => true,
574                _ => {
575                    return Err(PilError::ValueError("bad transparency mask".to_owned()));
576                }
577            }
578        } else {
579            false
580        };
581
582        let source_image = match source {
583            PasteSource::Image(image) => {
584                let source_mode = image.mode()?;
585                if source_mode == destination_mode
586                    || (destination_mode == "RGB"
587                        && matches!(source_mode.as_str(), "LA" | "RGBA" | "RGBa"))
588                {
589                    *image
590                } else if destination_mode == "RGBA" && source_mode == "RGB" && mask.is_none() {
591                    // Preserve native RGB bytes for the unmasked RGBA paste.
592                    // Each backend can copy RGB and supply opaque alpha in its
593                    // destination writer instead of materializing an RGBA
594                    // source image first.
595                    *image
596                } else if destination_mode == "PA" && source_mode == "P" {
597                    // Pillow promotes a P source to opaque PA samples before
598                    // pasting, retaining the source index byte verbatim.
599                    let mut promoted = *image;
600                    promoted.putalpha(255)?;
601                    promoted
602                } else {
603                    // Pillow Image.py converts a mismatched source before entering
604                    // libImaging/Paste.c. Keep that conversion shared by every
605                    // backend so CPU, GPU, and SIMD receive identical bytes.
606                    image.convert(&destination_mode, None, None, None, None)?
607                }
608            }
609            solid => {
610                let color = solid.solid_color(&destination_mode)?;
611                match color {
612                    ResolvedPasteColor::Bytes(color) if destination_mode == "P" => {
613                        let dims = CheckedDims::new(width, height, 1)?;
614                        let mut indices = dims.alloc_buffer();
615                        indices.fill(color.0);
616                        Image::frombytes("P", (width, height), &indices)?
617                    }
618                    ResolvedPasteColor::Bytes(color) if destination_mode == "PA" => {
619                        // PA's two raw bands use the same physical layout as LA;
620                        // the destination retains the palette and PA mode tag.
621                        Image::new(width, height, "LA", color)?
622                    }
623                    ResolvedPasteColor::Integer(value) => {
624                        let bytes = value.to_le_bytes();
625                        Image::new(width, height, "I", (bytes[0], bytes[1], bytes[2], bytes[3]))?
626                    }
627                    ResolvedPasteColor::Float(value) => {
628                        // Pillow's Paste.c writes scalar F-mode colors as the
629                        // destination's float32 sample, not as an integer byte.
630                        // Image::new stores F samples as their four raw LE bytes.
631                        let bytes = value.to_le_bytes();
632                        Image::new(width, height, "F", (bytes[0], bytes[1], bytes[2], bytes[3]))?
633                    }
634                    ResolvedPasteColor::Luma16(sample) => {
635                        // Pillow's Paste.c keeps I;16 scalar fills in unsigned
636                        // 16-bit storage. Construct the source with the same
637                        // native sample width; routing it through Image::new's
638                        // RGBA8 fallback would discard the high byte.
639                        let pixels = crate::raster::ImageBuffer::from_pixel(
640                            width,
641                            height,
642                            crate::raster::Luma([sample]),
643                        );
644                        Image::from_dynamic(
645                            crate::raster::DynamicImage::ImageLuma16(pixels),
646                            Some(destination_mode.clone()),
647                        )
648                    }
649                    ResolvedPasteColor::Bytes(color) => {
650                        Image::new(width, height, &destination_mode, color)?
651                    }
652                }
653            }
654        };
655
656        let w = i32::try_from(width)
657            .map_err(|_| PilError::ValueError("images do not match".to_owned()))?;
658        let h = i32::try_from(height)
659            .map_err(|_| PilError::ValueError("images do not match".to_owned()))?;
660        let new_self = Image::push_op(
661            self,
662            PipelineOp::Paste {
663                source: Arc::new(source_image),
664                x,
665                y,
666                w,
667                h,
668                mask: mask.map(|image| Arc::new(image.clone())),
669                mask_alpha,
670            },
671        );
672        *self = new_self;
673        Ok(())
674    }
675
676    /// Queues alpha compositing of `source` over this image.
677    ///
678    /// `dest` is the offset in the destination image and `src` is the offset in
679    /// the source image.
680    ///
681    /// # Errors
682    ///
683    /// Returns [`PilError::ValueError`] when source and destination dimensions
684    /// differ, or another [`PilError`] when size lookup fails.
685    pub fn alpha_composite(
686        &mut self,
687        source: &Image,
688        dest: (i32, i32),
689        src: (i32, i32),
690    ) -> Result<(), PilError> {
691        // Pillow 12.2.0 `libImaging/AlphaComposite.c::ImagingAlphaComposite`
692        // validates the destination mode first, then requires the source mode
693        // and dimensions to match exactly.
694        let dest_mode = self.mode()?;
695        if dest_mode != "RGBA" && dest_mode != "LA" {
696            return Err(PilError::ValueError("image has wrong mode".into()));
697        }
698        let source_mode = source.mode()?;
699        if source_mode != dest_mode {
700            return Err(PilError::ValueError("images do not match".into()));
701        }
702        let (w1, h1) = self.size()?;
703        let (w2, h2) = source.size()?;
704        if (w1, h1) != (w2, h2) {
705            return Err(PilError::ValueError("images do not match".into()));
706        }
707        let new_self = Image::push_op(
708            self,
709            PipelineOp::AlphaComposite {
710                source: Arc::new(source.clone()),
711                dest,
712                src,
713            },
714        );
715        *self = new_self;
716        Ok(())
717    }
718}
719
720fn byte_color(value: i64) -> Result<u8, PilError> {
721    u8::try_from(value).map_err(|_| PilError::TypeError("im must be Image or color".to_owned()))
722}
723
724fn clipped_byte(value: i64) -> u8 {
725    value.clamp(0, 255) as u8
726}
727
728fn paste_scalar_source(value: i64, mode: &str) -> PasteSource {
729    if matches!(mode, "I;16" | "I;16L" | "I;16B" | "I;16N") {
730        // Pillow's I;16 Paste.c path consumes the low byte of the Python
731        // integer and duplicates it across the unsigned sample. Keeping the
732        // source as the existing byte scalar preserves that behavior without
733        // involving the pending TIFF decoder lane.
734        PasteSource::Scalar(value.to_le_bytes()[0])
735    } else {
736        match u8::try_from(value) {
737            Ok(value) => PasteSource::Scalar(value),
738            Err(_) => PasteSource::RawScalar(value),
739        }
740    }
741}
742
743fn paste_source_from_color_string(value: &str, mode: &str) -> Result<PasteSource, PilError> {
744    // Pillow resolves a string through ImageColor.getcolor for the
745    // destination mode before entering Paste.c. Preserve that distinction
746    // from tuple colors: luma/alpha and RGBA modes carry different arities.
747    let (r, g, b, a) = crate::color::parse_color_str_unclamped(value)?;
748    let color = crate::color::getcolor(r, g, b, a, mode)?;
749    match color {
750        crate::color::ColorValue::Gray(value) => {
751            Ok(PasteSource::Scalar(byte_color(i64::from(value))?))
752        }
753        crate::color::ColorValue::GrayAlpha(value, alpha) => Ok(PasteSource::LumaAlpha(
754            byte_color(i64::from(value))?,
755            byte_color(i64::from(alpha))?,
756        )),
757        crate::color::ColorValue::Rgb(r, g, b) | crate::color::ColorValue::Hsv(r, g, b) => {
758            Ok(PasteSource::Rgb(
759                byte_color(i64::from(r))?,
760                byte_color(i64::from(g))?,
761                byte_color(i64::from(b))?,
762            ))
763        }
764        crate::color::ColorValue::Rgba(r, g, b, a) => Ok(PasteSource::Rgba(
765            byte_color(i64::from(r))?,
766            byte_color(i64::from(g))?,
767            byte_color(i64::from(b))?,
768            byte_color(i64::from(a))?,
769        )),
770    }
771}
772
773fn coordinate(value: i64) -> Result<i32, PilError> {
774    i32::try_from(value).map_err(|_| {
775        if value > i64::from(i32::MAX) {
776            PilError::OverflowError("signed integer is greater than maximum".into())
777        } else {
778            PilError::OverflowError("signed integer is less than minimum".into())
779        }
780    })
781}
782
783fn invalid_component_error(mode: &str) -> PilError {
784    let message = match mode {
785        "F" => "must be real number, not tuple",
786        "1" | "L" | "P" | "I" | "I;16" | "I;16L" | "I;16B" | "I;16N" => {
787            "color must be int or single-element tuple"
788        }
789        "LA" | "PA" => "color must be int, or tuple of one or two elements",
790        _ => "color must be int, or tuple of one, three or four elements",
791    };
792    PilError::TypeError(message.to_owned())
793}