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
9pub 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
36fn is_nonstandard_mode(mode: &str) -> bool {
40 matches!(mode, "CMYK" | "HSV" | "YCbCr" | "I" | "F" | "P" | "PA")
41}
42
43fn 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
54fn 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 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)), _ => Err(PilError::TypeError(
82 "'str' object cannot be interpreted as an integer".into(),
83 )),
84 }
85}
86
87#[derive(Debug, Clone)]
89pub enum PythonDitherInput {
90 None,
92 Integer(u32),
95 Name(String),
97 Invalid(String),
100}
101
102pub 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
120pub 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#[derive(Debug, Clone)]
140pub enum PythonConvertModeInput {
141 None,
143 Name(String),
145 Invalid(String),
147}
148
149#[derive(Debug, Clone)]
151pub enum PythonConvertPaletteInput {
152 None,
154 Name(String),
156 Invalid(String),
158}
159
160impl Image {
162 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 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 PythonConvertPaletteInput::Invalid(_) => None,
217 };
218 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 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 return Err(PilError::ValueError(
269 "conversion from La to L not supported".into(),
270 ));
271 }
272 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 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 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 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 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 return Image::from_dynamic(DynamicImage::ImageRgb8(straight.to_rgb8()), None)
355 .convert(mode, None, dither, _palette, _colors);
356 }
357 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 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 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 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 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 let luma = self.convert("L", None, None, None, None)?;
458 return luma.convert(mode, None, dither, _palette, _colors);
459 }
460
461 if is_luma16_mode(mode) {
467 if src_mode == "P" {
468 return Err(PilError::ValueError("conversion not supported".into()));
471 }
472 let samples = if src_mode == "I" && mode != "I;16N" {
473 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 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 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 if matches!(effective_src_mode_name, "I" | "F") && mode == "L" {
532 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 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 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 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 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 if is_nonstandard_mode(effective_src_mode_name)
661 && (target_is_standard
662 || mode == "CMYK"
663 || (mode == "PA" && effective_src_mode_name == "P"))
664 && !(effective_src_mode_name == "PA" && mode == "RGB")
671 {
672 let src_mode = effective_src_mode_name;
673 let palette = self.palette();
675 let shared = self.materialized_shared_for_ops()?;
679 let img = shared.as_ref();
680 if src_mode == "PA" && mode == "RGBA" {
681 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 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 let result = if mode == "CMYK" {
707 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 DynamicImage::ImageLuma8(ycbcr_luma8(img))
716 } else if mode == "LA" && src_mode == "YCbCr" {
717 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 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 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 DynamicImage::ImageRgb8(converted.into_rgb8())
767 } else if mode == "RGBA" {
768 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 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 }
796
797 let dither_enum = parse_dither(dither)?;
798
799 if mode == "1" {
802 if effective_src_mode == "CMYK" && matches!(dither_enum, Some(DitherMethod::None)) {
803 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 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 let use_threshold = matches!(dither_enum, Some(DitherMethod::None))
834 || matches!(effective_src_mode.as_str(), "P" | "PA");
835 if use_threshold {
836 for (op, gp) in out.pixels_mut().zip(gray.pixels()) {
838 op[0] = if gp[0] >= 128 { 255 } else { 0 };
839 }
840 } else {
841 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 if mode == "P" {
925 if src_mode == "RGBA" {
926 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 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 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 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 return Ok(Image::push_op(self, PipelineOp::Grayscale));
1020 }
1021 let pipeline_dither = if matches!(mode, "P" | "1") {
1028 dither_enum
1029 } else {
1030 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 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
1058fn identity_grayscale_palette() -> Vec<u8> {
1069 (0u8..=u8::MAX)
1070 .flat_map(|value| [value, value, value])
1071 .collect()
1072}
1073
1074fn 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 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 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 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 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 .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 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 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 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}