1pub mod cas;
2pub mod perceptual;
3
4use anyhow::Result;
5use bytes::Bytes;
6use fast_image_resize as fr;
7use image::GenericImageView;
8use img_parts::jpeg::Jpeg;
9use memmap2::Mmap;
10use perceptual::{FocusMode, PerceptualMetrics, PerceptualOptions};
11use serde::{Deserialize, Serialize};
12use std::fs;
13use std::path::{Path, PathBuf};
14#[cfg(target_os = "macos")]
15use std::sync::atomic::{AtomicUsize, Ordering};
16
17use image::ImageBuffer;
19use image::Rgba;
20
21#[cfg(target_os = "macos")]
22static SIPS_CONCURRENCY: AtomicUsize = AtomicUsize::new(0);
23#[cfg(target_os = "macos")]
24const MAX_SIPS_CONCURRENCY: usize = 4;
25
26#[derive(Clone, Copy, PartialEq, Debug, Serialize, Deserialize)]
27pub enum ProcessMode {
28 WeChat,
29 HD,
30 Custom,
31}
32
33#[derive(Clone, Copy, PartialEq, Debug, Serialize, Deserialize)]
34pub enum OutputFormat {
35 Jpeg,
36 KeepOriginal,
37 WebP,
39}
40
41#[derive(Clone, Copy, PartialEq, Debug, Serialize, Deserialize)]
42pub enum ColorSpace {
43 KeepOriginal,
44 ConvertToSRGB,
45}
46
47pub const APP_VERSION: &str = "v4.4.4";
50
51#[derive(Clone, Debug, Serialize, Deserialize)]
52pub struct AppConfig {
53 #[serde(default = "default_config_version")]
55 pub config_version: u32,
56 pub mode: ProcessMode,
57 pub custom_max_dim: u32,
58 pub custom_quality: u8,
59 pub custom_target_kb: u32,
60 pub overwrite: bool,
61 pub keep_original_name: bool,
62 pub output_format: OutputFormat,
63 pub color_space: ColorSpace,
64 pub enable_sharpening: bool, pub sharpening_radius: f32, pub sharpening_amount: f32, pub use_custom_quantization: bool, pub preserve_high_frequency: bool, #[serde(default = "default_usage_mode")]
76 pub usage_mode: String,
77 #[serde(default = "default_quality_mode")]
78 pub quality_mode: String,
79 #[serde(default = "default_platform")]
80 pub platform: String,
81 #[serde(default = "default_subsampling")]
83 pub subsampling: String,
84 #[serde(default)]
86 pub preserve_structure: bool,
87 #[serde(default)]
88 pub output_suffix: Option<String>,
89 #[serde(default)]
91 pub cas_strength: f32,
92 #[serde(default)]
94 pub custom_output_dir: Option<String>,
95}
96
97fn default_usage_mode() -> String {
98 "social".to_string()
99}
100fn default_config_version() -> u32 {
101 1
102}
103fn default_quality_mode() -> String {
104 "max".to_string()
105}
106fn default_platform() -> String {
107 "wechat".to_string()
108}
109
110fn default_subsampling() -> String {
111 "420".to_string()
112}
113
114impl Default for AppConfig {
115 fn default() -> Self {
116 Self {
117 config_version: 2,
118 mode: ProcessMode::Custom,
119 custom_max_dim: 3000,
120 custom_quality: 85,
121 custom_target_kb: 0,
122 overwrite: false,
123 keep_original_name: false,
124 output_format: OutputFormat::Jpeg,
125 color_space: ColorSpace::KeepOriginal,
126 enable_sharpening: false,
128 sharpening_radius: 1.0,
129 sharpening_amount: 0.8,
130 use_custom_quantization: false,
131 preserve_high_frequency: false,
132 usage_mode: "social".to_string(),
134 quality_mode: "max".to_string(),
135 platform: "wechat".to_string(),
136 subsampling: "420".to_string(),
137 preserve_structure: false,
138 output_suffix: None,
139 cas_strength: 0.0,
140 custom_output_dir: None,
141 }
142 }
143}
144
145#[derive(Clone, Debug)]
146pub struct ProcessConfig {
147 pub mode: ProcessMode,
148 pub max_dim: u32,
149 pub quality: u8,
150 pub target_kb: u32,
151 pub output_dir: Option<PathBuf>,
152 pub overwrite: bool,
153 pub keep_original_name: bool,
154 pub output_format: OutputFormat,
155 pub color_space: ColorSpace,
156 pub enable_sharpening: bool,
158 pub sharpening_radius: f32,
159 pub sharpening_amount: f32,
160 pub perceptual: Option<PerceptualOptions>,
162 pub subsampling: String,
164 pub preserve_structure: bool,
166 pub structure_base: Option<PathBuf>,
168 pub output_suffix: Option<String>,
170 pub cas_strength: f32,
172}
173
174pub struct Processor {
175 config: ProcessConfig,
176}
177
178impl Processor {
179 pub fn new(config: ProcessConfig) -> Self {
180 Self { config }
181 }
182
183 pub fn expected_output_path(&self, input_path: &Path) -> PathBuf {
191 let healed_path = path_self_healing(input_path);
192 let file_stem = healed_path
193 .file_stem()
194 .unwrap_or_default()
195 .to_string_lossy()
196 .to_string();
197 let extension = healed_path
198 .extension()
199 .and_then(|e| e.to_str())
200 .unwrap_or("")
201 .to_lowercase();
202
203 let output_ext = match self.config.output_format {
204 OutputFormat::Jpeg => "jpg",
205 OutputFormat::WebP => "webp",
206 OutputFormat::KeepOriginal => match extension.as_str() {
207 "png" => "png",
208 "webp" => "webp",
209 _ => "jpg",
210 },
211 };
212
213 let base_out = self
214 .config
215 .output_dir
216 .clone()
217 .unwrap_or_else(|| healed_path.parent().unwrap_or(Path::new(".")).to_path_buf());
218
219 let rel_parent = if self.config.preserve_structure {
221 self.config
222 .structure_base
223 .as_ref()
224 .and_then(|b| {
225 healed_path
226 .parent()
227 .unwrap_or(Path::new("."))
228 .strip_prefix(b)
229 .ok()
230 })
231 .unwrap_or_else(|| Path::new(""))
232 } else {
233 Path::new("")
234 };
235 let out_dir = base_out.join(rel_parent);
236
237 let suffix = if self.config.keep_original_name {
238 String::new()
239 } else if let Some(s) = &self.config.output_suffix {
240 if s.is_empty() {
241 String::new()
242 } else {
243 format!("_{}", s)
244 }
245 } else {
246 match self.config.mode {
247 ProcessMode::WeChat => "_wx".to_string(),
248 ProcessMode::HD => "_hd".to_string(),
249 _ => "_da".to_string(),
250 }
251 };
252
253 if self.config.overwrite {
254 healed_path.to_path_buf()
255 } else if self.config.keep_original_name {
256 out_dir.join(format!("{}.{}", file_stem, output_ext))
257 } else {
258 out_dir.join(format!("{}{}.{}", file_stem, suffix, output_ext))
259 }
260 }
261
262 pub fn passthrough_path(&self, input_path: &Path) -> PathBuf {
265 let healed_path = path_self_healing(input_path);
266 let base_out = self
267 .config
268 .output_dir
269 .clone()
270 .unwrap_or_else(|| healed_path.parent().unwrap_or(Path::new(".")).to_path_buf());
271 let rel_parent = if self.config.preserve_structure {
272 self.config
273 .structure_base
274 .as_ref()
275 .and_then(|b| {
276 healed_path
277 .parent()
278 .unwrap_or(Path::new("."))
279 .strip_prefix(b)
280 .ok()
281 })
282 .unwrap_or_else(|| Path::new(""))
283 } else {
284 Path::new("")
285 };
286 let out_dir = base_out.join(rel_parent);
287 let name = healed_path
288 .file_name()
289 .unwrap_or_default()
290 .to_string_lossy()
291 .to_string();
292 out_dir.join(name)
293 }
294
295 pub fn process_image(&self, input_path: &Path) -> Result<PathBuf> {
296 self.process_image_with_metrics(input_path).map(|(p, _)| p)
297 }
298
299 pub fn process_image_with_metrics(
301 &self,
302 input_path: &Path,
303 ) -> Result<(PathBuf, Option<PerceptualMetrics>)> {
304 let healed_path = path_self_healing(input_path);
305 let file_name_os = healed_path
306 .file_name()
307 .unwrap_or_default()
308 .to_string_lossy();
309 if file_name_os.starts_with("._") {
310 return Err(anyhow::anyhow!("跳过系统隐藏文件"));
311 }
312
313 let extension = healed_path
314 .extension()
315 .and_then(|e| e.to_str())
316 .unwrap_or("")
317 .to_lowercase();
318
319 let raw_extensions = [
320 "dng", "cr2", "cr3", "nef", "arw", "orf", "raf", "rw2", "pef", "srw", "3fr",
321 ];
322 let is_raw = raw_extensions.contains(&extension.as_str());
323
324 let output_path = self.expected_output_path(&healed_path);
326 if let Some(parent) = output_path.parent() {
327 fs::create_dir_all(parent)?;
328 }
329
330 let metrics: Option<PerceptualMetrics>;
331
332 #[cfg(target_os = "macos")]
333 {
334 let file_stem = healed_path.file_stem().unwrap().to_string_lossy();
335 if is_raw {
336 self.process_raw(&healed_path, &output_path, &file_stem, &file_name_os)?;
337 metrics = None;
338 } else {
339 metrics = self.process_normal(&healed_path, &output_path, &extension)?;
340 }
341 }
342
343 #[cfg(not(target_os = "macos"))]
344 if is_raw {
345 return Err(anyhow::anyhow!(
346 "RAW 格式 ({}) 仅在 macOS 系统上支持。请先在 Mac 上处理,或转成 JPG/PNG 后使用。",
347 extension
348 ));
349 } else {
350 metrics = self.process_normal(&healed_path, &output_path, &extension)?;
351 }
352
353 Ok((output_path, metrics))
354 }
355
356 pub fn perceptual_config(&self) -> Option<&PerceptualOptions> {
358 self.config.perceptual.as_ref()
359 }
360
361 pub fn effective_target_kb(&self) -> u32 {
363 match &self.config.perceptual {
364 Some(p) => p.budget_kb.unwrap_or(self.config.target_kb),
365 None => self.config.target_kb,
366 }
367 }
368
369 #[cfg(target_os = "macos")]
370 fn process_raw(
371 &self,
372 input_path: &Path,
373 output_path: &Path,
374 file_stem: &str,
375 file_name: &str,
376 ) -> Result<()> {
377 while SIPS_CONCURRENCY.load(Ordering::SeqCst) >= MAX_SIPS_CONCURRENCY {
378 std::thread::sleep(std::time::Duration::from_millis(100));
379 }
380 SIPS_CONCURRENCY.fetch_add(1, Ordering::SeqCst);
381
382 let input_path_abs =
383 fs::canonicalize(input_path).unwrap_or_else(|_| input_path.to_path_buf());
384 let result = (|| -> Result<()> {
385 let mut preview_cmd = std::process::Command::new("sips");
386 preview_cmd
387 .arg("-e")
388 .arg("preview")
389 .arg(&input_path_abs)
390 .arg("--out")
391 .arg(output_path);
392
393 let _ = preview_cmd.output();
394 if output_path.exists() {
395 if self.config.max_dim > 0 {
397 if let Ok(img) = image::open(output_path) {
398 let (w, h) = img.dimensions();
399 if w > self.config.max_dim || h > self.config.max_dim {
400 let mut resize_cmd = std::process::Command::new("sips");
401 resize_cmd.arg("-Z").arg(self.config.max_dim.to_string());
402 resize_cmd.arg(output_path);
403 let _ = resize_cmd.output();
404 }
405 }
406 }
407 return Ok(());
408 }
409
410 let mut cmd = std::process::Command::new("sips");
411 cmd.arg("-s").arg("format").arg("jpeg");
412 let quality = self.config.quality;
413 cmd.arg("-s").arg("formatOptions").arg(quality.to_string());
414 if self.config.max_dim > 0 {
415 cmd.arg("-Z").arg(self.config.max_dim.to_string());
416 }
417 cmd.arg(&input_path_abs).arg("--out").arg(output_path);
418
419 let mut child = cmd.spawn()?;
420 let timeout = std::time::Duration::from_secs(30);
421 let start = std::time::Instant::now();
422
423 let status = loop {
424 match child.try_wait()? {
425 Some(status) => break status,
426 None => {
427 if start.elapsed() > timeout {
428 let _ = child.kill();
429 break std::process::ExitStatus::default();
430 }
431 std::thread::sleep(std::time::Duration::from_millis(100));
432 }
433 }
434 };
435
436 if status.success() && output_path.exists() {
437 return Ok(());
438 }
439
440 let temp_dir = std::env::temp_dir().join("rust_compressor_ql");
441 let _ = fs::create_dir_all(&temp_dir);
442 let mut ql_cmd = std::process::Command::new("qlmanage");
443 ql_cmd.arg("-t").arg("-s");
444 if self.config.max_dim > 0 {
446 ql_cmd.arg(self.config.max_dim.to_string());
447 } else {
448 ql_cmd.arg("20000");
449 }
450 ql_cmd.arg("-o").arg(&temp_dir).arg(&input_path_abs);
451
452 if let Ok(mut child) = ql_cmd.spawn() {
453 let start = std::time::Instant::now();
454 loop {
455 if let Ok(Some(_)) = child.try_wait() {
456 break;
457 }
458 if start.elapsed().as_secs() > 30 {
459 let _ = child.kill();
460 break;
461 }
462 std::thread::sleep(std::time::Duration::from_millis(100));
463 }
464 }
465
466 let ql_file_1 = temp_dir.join(format!("{}.png", file_stem));
467 let ql_file_2 = temp_dir.join(format!("{}.png", file_name));
468 let ql_file = if ql_file_1.exists() {
469 Some(ql_file_1)
470 } else if ql_file_2.exists() {
471 Some(ql_file_2)
472 } else {
473 None
474 };
475
476 if let Some(path) = ql_file {
477 let mut conv_cmd = std::process::Command::new("sips");
478 conv_cmd
479 .arg("-s")
480 .arg("format")
481 .arg("jpeg")
482 .arg(&path)
483 .arg("--out")
484 .arg(output_path);
485 let _ = conv_cmd.output();
486 let _ = fs::remove_file(path);
487 if output_path.exists() {
488 return Ok(());
489 }
490 }
491
492 Err(anyhow::anyhow!("该机型 RAW 暂不支持"))
493 })();
494
495 SIPS_CONCURRENCY.fetch_sub(1, Ordering::SeqCst);
496 result?;
497 Ok(())
498 }
499
500 fn process_normal(
501 &self,
502 input_path: &Path,
503 output_path: &Path,
504 extension: &str,
505 ) -> Result<Option<PerceptualMetrics>> {
506 let img = load_image_safe(input_path)?;
507 let (width, height) = img.dimensions();
508 let src_has_alpha = img.color().has_alpha();
511 let perceptual = self.config.perceptual.as_ref();
512 let mut pm = PerceptualMetrics::default();
513
514 let scale = if self.config.max_dim > 0
516 && (width > self.config.max_dim || height > self.config.max_dim)
517 {
518 let ratio_w = self.config.max_dim as f32 / width as f32;
519 let ratio_h = self.config.max_dim as f32 / height as f32;
520 ratio_w.min(ratio_h)
521 } else {
522 1.0
523 };
524
525 let new_width = (width as f32 * scale) as u32;
526 let new_height = (height as f32 * scale) as u32;
527
528 let img_rgba = img.to_rgba8();
529
530 let t_down = std::time::Instant::now();
531 let src_image = fr::images::Image::from_vec_u8(
532 width,
533 height,
534 img_rgba.into_raw(),
535 fr::PixelType::U8x4,
536 )?;
537
538 let mut dst_image = fr::images::Image::new(new_width, new_height, fr::PixelType::U8x4);
539
540 let mut resizer = fr::Resizer::new();
541 resizer.resize(&src_image, &mut dst_image, None)?;
542
543 let rgba_buf = dst_image.buffer();
544 pm.downscale_ms = t_down.elapsed().as_millis() as u64;
545
546 let mut dynamic_img = image::DynamicImage::ImageRgba8(
548 image::ImageBuffer::from_raw(new_width, new_height, rgba_buf.to_vec())
549 .ok_or_else(|| anyhow::anyhow!("Failed to create image buffer"))?,
550 );
551
552 let reference_gray = perceptual.map(|_| perceptual::to_gray(&dynamic_img));
554
555 if let Some(p) = perceptual {
556 let is_jpeg_input = matches!(extension, "jpg" | "jpeg");
560 if p.denoise_strength > 0 && !is_jpeg_input && new_width.max(new_height) <= 4000 {
561 let t = std::time::Instant::now();
562 dynamic_img = image::DynamicImage::ImageRgba8(perceptual::bilateral_denoise(
563 &dynamic_img.to_rgba8(),
564 p.denoise_strength,
565 ));
566 pm.denoise_ms = t.elapsed().as_millis() as u64;
567 pm.denoise_applied = true;
568 }
569 let t = std::time::Instant::now();
571 let rgba_now = dynamic_img.to_rgba8();
572 let mask = match p.focus_mode {
573 FocusMode::Auto => perceptual::saliency_mask(&rgba_now),
574 FocusMode::Center => perceptual::center_mask(new_width, new_height),
575 };
576 let larger = new_width.max(new_height);
577 let (radius, amount, threshold) = if larger < 1500 {
579 (0.7, 0.55, 6)
580 } else if larger < 3000 {
581 (0.9, 0.7, 5)
582 } else {
583 (1.1, 0.8, 4)
584 };
585 dynamic_img =
586 perceptual::masked_usm_sharpen(&dynamic_img, &mask, radius, amount, threshold);
587 pm.sharpen_ms = t.elapsed().as_millis() as u64;
588 } else if self.config.cas_strength > 0.0 && scale < (1.0 / 1.3) {
589 let t = std::time::Instant::now();
593 let adaptive_strength =
594 compute_adaptive_cas_strength(&dynamic_img, scale, self.config.cas_strength);
595 if adaptive_strength > 0.0 {
596 dynamic_img = cas::cas_sharpen(&dynamic_img, adaptive_strength);
597 }
598 pm.sharpen_ms = t.elapsed().as_millis() as u64;
599 } else if self.config.enable_sharpening {
600 dynamic_img = smart_adaptive_sharpen(&dynamic_img, new_width.max(new_height));
602 }
603
604 let mut result_data;
605 use std::io::Cursor;
606
607 let output_ext = match self.config.output_format {
608 OutputFormat::Jpeg => "jpg",
609 OutputFormat::WebP => "webp",
610 OutputFormat::KeepOriginal => match extension {
611 "png" => "png",
612 "webp" => "webp",
613 _ => "jpg",
614 },
615 };
616
617 match output_ext {
618 "png" => {
619 use image::codecs::png::{CompressionType, FilterType, PngEncoder};
620 let mut cursor = Cursor::new(Vec::new());
621 let encoder = PngEncoder::new_with_quality(
622 &mut cursor,
623 CompressionType::Best,
624 FilterType::Adaptive,
625 );
626 dynamic_img.write_with_encoder(encoder)?;
627 result_data = cursor.into_inner();
628 }
629 "webp" => {
630 let mut cursor = Cursor::new(Vec::new());
631 dynamic_img.write_to(&mut cursor, image::ImageFormat::WebP)?;
632 result_data = cursor.into_inner();
633 }
634 _ => {
635 let t_encode = std::time::Instant::now();
636 let rgb_buf: Vec<u8> = if src_has_alpha {
638 flatten_rgba8_to_rgb(dynamic_img.to_rgba8())
639 } else {
640 dynamic_img.to_rgb8().into_raw()
641 };
642
643 let effective_target_kb = match perceptual {
645 Some(p) => p.budget_kb.unwrap_or(self.config.target_kb),
646 None => self.config.target_kb,
647 };
648 let limit_bytes = if effective_target_kb > 0 {
649 Some((effective_target_kb as usize) * 1024)
650 } else {
651 None
652 };
653
654 let quant_mode = perceptual.map(|p| p.quant_mode);
655 let encode_jpeg = |quality: u8| -> Result<Vec<u8>, anyhow::Error> {
656 use mozjpeg_rs::{Encoder, QuantTableIdx, Subsampling};
657 let sub = match self.config.subsampling.as_str() {
660 "444" => Subsampling::S444,
661 "422" => Subsampling::S422,
662 _ => Subsampling::S420, };
664 let mut encoder = Encoder::default()
665 .quality(quality)
666 .progressive(true)
667 .optimize_huffman(true)
668 .subsampling(sub);
669 match quant_mode {
672 Some(perceptual::QuantMode::MsSsim) | Some(perceptual::QuantMode::Csf) => {
673 encoder = encoder.quant_tables(QuantTableIdx::MssimTuned);
674 }
675 _ => {} }
677 encoder
678 .encode_rgb(&rgb_buf, new_width, new_height)
679 .map_err(|e| anyhow::anyhow!("JPEG encoding failed: {}", e))
680 };
681
682 if let Some(limit) = limit_bytes {
683 let current_q = match perceptual {
684 Some(p) => self.config.quality.min(p.quality_ceil),
685 None => self.config.quality,
686 };
687 pm.final_quality = current_q;
688 let data = encode_jpeg(current_q)?;
689
690 if data.len() <= limit {
691 result_data = data;
692 } else {
693 let mut low = 1;
694 let mut high = current_q - 1;
695 let mut best_data = Vec::new();
696
697 while low <= high {
698 let mid = (low + high) / 2;
699 if mid == 0 {
700 break;
701 }
702
703 if let Ok(data) = encode_jpeg(mid) {
704 if data.len() <= limit {
705 best_data = data;
706 pm.final_quality = mid;
707 low = mid + 1;
708 } else {
709 if mid == 0 {
710 break;
711 }
712 high = mid - 1;
713 }
714 } else {
715 break;
716 }
717 }
718
719 if !best_data.is_empty() {
720 result_data = best_data;
721 } else {
722 result_data = encode_jpeg(1)?;
723 pm.final_quality = 1;
724 }
725 }
726 } else {
727 let q = match perceptual {
728 Some(p) => self.config.quality.min(p.quality_ceil),
729 None => self.config.quality,
730 };
731 pm.final_quality = q;
732 result_data = encode_jpeg(q)?;
733 }
734 pm.encode_ms = t_encode.elapsed().as_millis() as u64;
735
736 if let (Some(_), Some((ref_gray, gw, gh))) = (perceptual, reference_gray.as_ref()) {
738 if let Ok(decoded) = image::load_from_memory(&result_data) {
739 let (out_gray, ow, oh) = perceptual::to_gray(&decoded);
740 if ow == *gw && oh == *gh {
741 pm.ssim_vs_source =
742 perceptual::ssim_gray(ref_gray, &out_gray, *gw, *gh);
743 pm.psnr_vs_source = perceptual::psnr_gray(ref_gray, &out_gray);
744 }
745 }
746 }
747
748 if extension == "jpg" || extension == "jpeg" {
749 result_data = preserve_exif_safe(input_path, &result_data);
750 }
751 }
752 }
753
754 fs::write(output_path, result_data)?;
755 Ok(perceptual.map(|_| pm))
756 }
757}
758
759fn preserve_exif_safe(input_path: &Path, result_data: &[u8]) -> Vec<u8> {
760 let input_file = match fs::File::open(input_path) {
761 Ok(file) => file,
762 Err(_) => return result_data.to_vec(),
763 };
764
765 let input_mmap = match unsafe { Mmap::map(&input_file) } {
766 Ok(mmap) => mmap,
767 Err(_) => return result_data.to_vec(),
768 };
769
770 if input_mmap.len() > 100 * 1024 * 1024 {
771 return result_data.to_vec();
772 }
773
774 let input_jpeg = match Jpeg::from_bytes(Bytes::copy_from_slice(&input_mmap)) {
775 Ok(jpeg) => jpeg,
776 Err(_) => return result_data.to_vec(),
777 };
778
779 let meta_segments: Vec<_> = input_jpeg
785 .segments()
786 .iter()
787 .filter(|s| (0xE0..=0xEF).contains(&s.marker()))
788 .cloned()
789 .collect();
790 if meta_segments.is_empty() {
791 return result_data.to_vec();
792 }
793
794 drop(input_mmap);
795 drop(input_file);
796
797 let output_jpeg = match Jpeg::from_bytes(Bytes::copy_from_slice(result_data)) {
798 Ok(jpeg) => jpeg,
799 Err(_) => return result_data.to_vec(),
800 };
801
802 let mut output_jpeg = output_jpeg;
803 let mut insert_pos = 1;
805 for seg in &meta_segments {
806 output_jpeg.segments_mut().insert(insert_pos, seg.clone());
807 insert_pos += 1;
808 }
809 output_jpeg.encoder().bytes().to_vec()
810}
811
812pub fn app_config_to_process_config(
822 config: &AppConfig,
823 output_dir: Option<PathBuf>,
824) -> ProcessConfig {
825 let (mode, max_dim, quality, target_kb) = match config.usage_mode.as_str() {
826 "social" => (
827 ProcessMode::WeChat,
828 config.custom_max_dim,
829 config.custom_quality,
830 config.custom_target_kb,
831 ),
832 "archive" => (ProcessMode::HD, 0, 95, 0),
835 _ => {
836 match config.mode {
838 ProcessMode::HD => (ProcessMode::HD, 4096, 95, 5000),
839 ProcessMode::WeChat => (ProcessMode::WeChat, 2048, 95, 900),
840 ProcessMode::Custom => (
841 ProcessMode::Custom,
842 config.custom_max_dim,
843 config.custom_quality,
844 config.custom_target_kb,
845 ),
846 }
847 }
848 };
849 ProcessConfig {
850 mode,
851 max_dim,
852 quality,
853 target_kb,
854 output_dir,
855 overwrite: config.overwrite,
856 keep_original_name: config.keep_original_name,
857 output_format: config.output_format,
858 color_space: config.color_space,
859 subsampling: config.subsampling.clone(),
860 preserve_structure: config.preserve_structure,
862 structure_base: None, output_suffix: config.output_suffix.clone(),
864 cas_strength: config.cas_strength,
866 enable_sharpening: config.enable_sharpening,
868 sharpening_radius: config.sharpening_radius,
869 sharpening_amount: config.sharpening_amount,
870 perceptual: None,
871 }
872}
873
874pub(crate) fn is_skin_color(r: u8, g: u8, b: u8) -> f32 {
883 let _y = 0.299 * r as f32 + 0.587 * g as f32 + 0.114 * b as f32;
885 let cb = -0.1687 * r as f32 - 0.3313 * g as f32 + 0.5 * b as f32 + 128.0;
886 let cr = 0.5 * r as f32 - 0.4187 * g as f32 - 0.0813 * b as f32 + 128.0;
887
888 let cb_min = 77.0;
890 let cb_max = 127.0;
891 let cr_min = 133.0;
892 let cr_max = 173.0;
893
894 if cb >= cb_min && cb <= cb_max && cr >= cr_min && cr <= cr_max {
895 let cb_score = 1.0 - ((cb - (cb_min + cb_max) / 2.0) / ((cb_max - cb_min) / 2.0)).abs();
897 let cr_score = 1.0 - ((cr - (cr_min + cr_max) / 2.0) / ((cr_max - cr_min) / 2.0)).abs();
898 (cb_score * cr_score).clamp(0.0, 1.0)
899 } else {
900 0.0
901 }
902}
903
904pub(crate) fn estimate_skin_ratio(image: &image::DynamicImage) -> f32 {
908 let rgba = image.to_rgba8();
909 let (width, height) = rgba.dimensions();
910
911 let sample_step = 20;
913 let mut skin_count = 0;
914 let mut total_count = 0;
915
916 for y in (0..height).step_by(sample_step as usize) {
917 for x in (0..width).step_by(sample_step as usize) {
918 let pixel = rgba.get_pixel(x, y);
919 let skin_score = is_skin_color(pixel[0], pixel[1], pixel[2]);
920 if skin_score > 0.3 {
921 skin_count += 1;
922 }
923 total_count += 1;
924 }
925 }
926
927 if total_count == 0 {
928 return 0.0;
929 }
930
931 skin_count as f32 / total_count as f32
932}
933
934fn should_apply_sharpening(image: &image::DynamicImage, _max_dim: u32) -> bool {
942 let (width, height) = image.dimensions();
943 let larger_dim = width.max(height);
944
945 if larger_dim < 800 {
947 return false;
948 }
949
950 let skin_ratio = estimate_skin_ratio(image);
952
953 if skin_ratio > 0.3 {
955 return estimate_image_complexity(image) > 0.5;
957 }
958
959 if larger_dim < 2000 {
961 return estimate_image_complexity(image) > 0.3;
963 }
964
965 if larger_dim >= 2000 {
967 if is_already_sharp_enough(image) {
969 return false;
970 }
971
972 if estimate_noise_level(image) > 0.6 {
974 return false;
975 }
976
977 return true;
978 }
979
980 true
981}
982
983fn estimate_image_complexity(image: &image::DynamicImage) -> f32 {
986 let rgba = image.to_rgba8();
987 let (width, height) = rgba.dimensions();
988
989 let sample_w = (width / 100).max(1);
991 let sample_h = (height / 100).max(1);
992
993 let mut complexity_sum = 0.0f32;
994 let mut count = 0;
995
996 for y in (0..height).step_by(sample_h as usize) {
997 for x in (0..width).step_by(sample_w as usize) {
998 let pixel = rgba.get_pixel(x, y);
999
1000 let mut neighbors = Vec::new();
1002 if x > 0 {
1003 neighbors.push(rgba.get_pixel(x - 1, y));
1004 }
1005 if x < width - 1 {
1006 neighbors.push(rgba.get_pixel(x + 1, y));
1007 }
1008 if y > 0 {
1009 neighbors.push(rgba.get_pixel(x, y - 1));
1010 }
1011 if y < height - 1 {
1012 neighbors.push(rgba.get_pixel(x, y + 1));
1013 }
1014
1015 if !neighbors.is_empty() {
1016 let variance = neighbors
1017 .iter()
1018 .map(|n| {
1019 ((pixel[0] as i16 - n[0] as i16).abs() as f32
1020 + (pixel[1] as i16 - n[1] as i16).abs() as f32
1021 + (pixel[2] as i16 - n[2] as i16).abs() as f32)
1022 / 3.0
1023 })
1024 .sum::<f32>()
1025 / neighbors.len() as f32;
1026
1027 complexity_sum += variance;
1028 count += 1;
1029 }
1030 }
1031 }
1032
1033 if count == 0 {
1034 return 0.0;
1035 }
1036
1037 let avg_complexity = complexity_sum / count as f32;
1039 (avg_complexity / 50.0).clamp(0.0, 1.0)
1040}
1041
1042fn is_already_sharp_enough(image: &image::DynamicImage) -> bool {
1044 let complexity = estimate_image_complexity(image);
1045 complexity > 0.7
1047}
1048
1049fn estimate_noise_level(image: &image::DynamicImage) -> f32 {
1052 let rgba = image.to_rgba8();
1053 let (width, height) = rgba.dimensions();
1054
1055 let mut noise_scores = Vec::new();
1057
1058 let step = 20;
1060 for y in (0..height).step_by(step) {
1061 for x in (0..width).step_by(step) {
1062 let mut region_pixels = Vec::new();
1064 for dy in 0..3.min(height - y) {
1065 for dx in 0..3.min(width - x) {
1066 region_pixels.push(rgba.get_pixel(x + dx, y + dy));
1067 }
1068 }
1069
1070 if region_pixels.len() >= 4 {
1071 let mean_r = region_pixels.iter().map(|p| p[0] as f32).sum::<f32>()
1073 / region_pixels.len() as f32;
1074 let variance = region_pixels
1075 .iter()
1076 .map(|p| (p[0] as f32 - mean_r).powi(2))
1077 .sum::<f32>()
1078 / region_pixels.len() as f32;
1079
1080 if variance < 100.0 {
1082 noise_scores.push(variance);
1084 }
1085 }
1086 }
1087 }
1088
1089 if noise_scores.is_empty() {
1090 return 0.0;
1091 }
1092
1093 let avg_noise = noise_scores.iter().sum::<f32>() / noise_scores.len() as f32;
1094 (avg_noise / 50.0).min(1.0)
1096}
1097
1098fn smart_adaptive_sharpen(image: &image::DynamicImage, max_dim: u32) -> image::DynamicImage {
1107 if !should_apply_sharpening(image, max_dim) {
1109 return image.clone();
1110 }
1111
1112 let (width, height) = image.dimensions();
1113 let larger_dim = width.max(height);
1114
1115 let skin_ratio = estimate_skin_ratio(image);
1117 let is_portrait = skin_ratio > 0.3;
1118 let complexity = estimate_image_complexity(image);
1119
1120 let (radius, mut amount, threshold) = if is_portrait {
1122 if larger_dim < 2000 {
1124 (0.6, 0.3, 15) } else if larger_dim < 4000 {
1126 (0.8, 0.4, 12) } else {
1128 (1.0, 0.5, 10) }
1130 } else {
1131 if larger_dim < 2000 {
1133 if complexity > 0.5 {
1134 (0.8, 0.6, 10) } else {
1136 (0.6, 0.4, 15) }
1138 } else if larger_dim < 4000 {
1139 if complexity > 0.5 {
1140 (1.0, 0.8, 6) } else {
1142 (0.8, 0.6, 8) }
1144 } else if complexity > 0.5 {
1145 (1.5, 1.0, 4) } else {
1147 (1.2, 0.8, 5) }
1149 };
1150
1151 if larger_dim < 1500 {
1153 amount *= 0.7;
1154 }
1155
1156 apply_usm_sharpen(image, radius, amount, threshold)
1157}
1158
1159fn compute_adaptive_cas_strength(image: &image::DynamicImage, scale: f32, max_cas: f32) -> f32 {
1164 let (width, height) = image.dimensions();
1165 let larger_dim = width.max(height);
1166
1167 if larger_dim < 800 {
1169 return 0.0;
1170 }
1171
1172 let skin_ratio = estimate_skin_ratio(image);
1173 let complexity = estimate_image_complexity(image);
1174 let noise = estimate_noise_level(image);
1175 let is_portrait = skin_ratio > 0.3;
1176
1177 if noise > 0.6 {
1179 return 0.0;
1180 }
1181 if is_already_sharp_enough(image) {
1183 return 0.0;
1184 }
1185 if is_portrait && complexity <= 0.5 {
1188 return 0.0;
1189 }
1190 if larger_dim < 2000 && complexity <= 0.3 {
1192 return 0.0;
1193 }
1194
1195 let base: f32 = if is_portrait {
1197 if larger_dim < 2000 {
1199 0.08
1200 } else if larger_dim < 4000 {
1201 0.14
1202 } else {
1203 0.22
1204 }
1205 } else {
1206 if complexity > 0.5 {
1208 if larger_dim < 2000 {
1209 0.18
1210 } else if larger_dim < 4000 {
1211 0.30
1212 } else {
1213 0.44
1214 }
1215 } else if larger_dim < 2000 {
1216 0.12
1217 } else if larger_dim < 4000 {
1218 0.22
1219 } else {
1220 0.34
1221 }
1222 };
1223
1224 let scale_factor = ((1.0 - scale) / 0.9).clamp(0.0, 1.0).powf(0.5);
1226
1227 let size_penalty = if larger_dim < 1500 { 0.6 } else { 1.0 };
1229
1230 let noise_penalty = if noise > 0.4 { 0.75 } else { 1.0 };
1232
1233 let adaptive = (base * scale_factor * size_penalty * noise_penalty).clamp(0.0, 0.5);
1234
1235 adaptive.min(max_cas)
1237}
1238
1239fn apply_usm_sharpen(
1259 image: &image::DynamicImage,
1260 radius: f32,
1261 amount: f32,
1262 threshold: u8,
1263) -> image::DynamicImage {
1264 let rgba = image.to_rgba8();
1265 let (width, height) = rgba.dimensions();
1266
1267 let sigma = radius;
1269 let blurred = gaussian_blur(&rgba, sigma);
1270
1271 let skin_ratio = estimate_skin_ratio(image);
1273 let is_portrait = skin_ratio > 0.3;
1274
1275 let mut output = ImageBuffer::new(width, height);
1277
1278 for y in 0..height {
1280 for x in 0..width {
1281 let orig_pixel = rgba.get_pixel(x, y);
1282 let blur_pixel = blurred.get_pixel(x, y);
1283
1284 let mut out_pixel = Rgba([0u8; 4]);
1285
1286 let skin_score = is_skin_color(orig_pixel[0], orig_pixel[1], orig_pixel[2]);
1288 let skin_factor = if is_portrait && skin_score > 0.3 {
1289 1.0 - skin_score * 0.8
1291 } else {
1292 1.0
1294 };
1295
1296 for c in 0..3 {
1297 let diff = orig_pixel[c] as i16 - blur_pixel[c] as i16;
1299
1300 if diff.abs() > threshold as i16 {
1302 let effective_amount = amount * skin_factor;
1304 let sharpened = orig_pixel[c] as i32 + (effective_amount * diff as f32) as i32;
1305 out_pixel[c] = sharpened.clamp(0, 255) as u8;
1306 } else {
1307 out_pixel[c] = orig_pixel[c];
1308 }
1309 }
1310
1311 out_pixel[3] = orig_pixel[3];
1313
1314 output.put_pixel(x, y, out_pixel);
1315 }
1316 }
1317
1318 image::DynamicImage::ImageRgba8(output)
1319}
1320
1321pub(crate) fn gaussian_blur(
1328 image: &ImageBuffer<Rgba<u8>, Vec<u8>>,
1329 sigma: f32,
1330) -> ImageBuffer<Rgba<u8>, Vec<u8>> {
1331 let (width, height) = image.dimensions();
1332
1333 let kernel_size = ((sigma * 6.0) as usize).max(3) | 1; let half_kernel = kernel_size / 2;
1336
1337 let kernel = generate_1d_gaussian_kernel(kernel_size, sigma);
1339
1340 let mut temp = ImageBuffer::new(width, height);
1342 for y in 0..height {
1343 for x in 0..width {
1344 let mut pixel = Rgba([0u8; 4]);
1345 for c in 0..4 {
1346 let mut sum = 0.0f32;
1347 let mut weight_sum = 0.0f32;
1348 for (kx, &weight) in kernel.iter().enumerate() {
1349 let px = (x as i32 + kx as i32 - half_kernel as i32).clamp(0, width as i32 - 1)
1350 as u32;
1351 let sample_pixel = image.get_pixel(px, y);
1352 sum += sample_pixel[c] as f32 * weight;
1353 weight_sum += weight;
1354 }
1355 pixel[c] = (sum / weight_sum).clamp(0.0, 255.0) as u8;
1356 }
1357 temp.put_pixel(x, y, pixel);
1358 }
1359 }
1360
1361 let mut output = ImageBuffer::new(width, height);
1363 for y in 0..height {
1364 for x in 0..width {
1365 let mut pixel = Rgba([0u8; 4]);
1366 for c in 0..4 {
1367 let mut sum = 0.0f32;
1368 let mut weight_sum = 0.0f32;
1369 for (ky, &weight) in kernel.iter().enumerate() {
1370 let py = (y as i32 + ky as i32 - half_kernel as i32).clamp(0, height as i32 - 1)
1371 as u32;
1372 let sample_pixel = temp.get_pixel(x, py);
1373 sum += sample_pixel[c] as f32 * weight;
1374 weight_sum += weight;
1375 }
1376 pixel[c] = (sum / weight_sum).clamp(0.0, 255.0) as u8;
1377 }
1378 output.put_pixel(x, y, pixel);
1379 }
1380 }
1381
1382 output
1383}
1384
1385fn generate_1d_gaussian_kernel(size: usize, sigma: f32) -> Vec<f32> {
1387 let mut kernel = vec![0.0f32; size];
1388 let half = (size / 2) as f32;
1389 let two_sigma_sq = 2.0 * sigma * sigma;
1390
1391 let mut sum = 0.0f32;
1392 for (x, val) in kernel.iter_mut().enumerate() {
1393 let dx = x as f32 - half;
1394 let value = (-dx * dx / two_sigma_sq).exp();
1395 *val = value;
1396 sum += value;
1397 }
1398
1399 for val in kernel.iter_mut() {
1401 *val /= sum;
1402 }
1403
1404 kernel
1405}
1406
1407#[allow(dead_code)]
1418fn manage_color_space(
1419 image: image::DynamicImage,
1420 max_dim: u32,
1421 has_300dpi: bool,
1422) -> image::DynamicImage {
1423 if has_300dpi || max_dim > 4000 {
1425 return image;
1426 }
1427
1428 if max_dim <= 3000 {
1430 return image;
1433 }
1434
1435 image
1437}
1438
1439#[allow(dead_code)]
1441fn is_high_resolution_dpi(input_path: &Path) -> bool {
1442 if let Ok(file) = fs::File::open(input_path) {
1444 if let Ok(mmap) = unsafe { Mmap::map(&file) } {
1445 if mmap.len() > 5 * 1024 * 1024 {
1447 return true;
1448 }
1449 }
1450 }
1451 false
1452}
1453
1454pub fn path_self_healing(input_path: &Path) -> PathBuf {
1455 let path_str = input_path.to_string_lossy();
1456
1457 if input_path.exists() && input_path.is_file() {
1458 return input_path.to_path_buf();
1459 }
1460
1461 if let Some(file_name) = input_path.file_name().and_then(|n| n.to_str()) {
1462 if let Some(parent) = input_path.parent() {
1463 if parent.exists() {
1464 if let Ok(entries) = fs::read_dir(parent) {
1465 for entry in entries.flatten() {
1466 if let Some(name) = entry.file_name().to_str() {
1467 if name.eq_ignore_ascii_case(file_name) {
1468 let candidate = entry.path();
1469 if candidate.is_file() {
1470 return candidate;
1471 }
1472 }
1473 }
1474 }
1475 }
1476 }
1477
1478 if let Ok(entries) = fs::read_dir(parent) {
1479 for entry in entries.flatten() {
1480 if let Some(name) = entry.file_name().to_str() {
1481 if name.to_lowercase() == file_name.to_lowercase() {
1482 let candidate = entry.path();
1483 if candidate.is_file() {
1484 return candidate;
1485 }
1486 }
1487 }
1488 }
1489 }
1490 }
1491 }
1492
1493 let normalized = path_str.replace("\\", "/");
1494 if normalized != path_str {
1495 let alt_path = Path::new(&normalized);
1496 if alt_path.exists() && alt_path.is_file() {
1497 return alt_path.to_path_buf();
1498 }
1499 }
1500
1501 input_path.to_path_buf()
1502}
1503
1504fn load_image_safe(input_path: &Path) -> Result<image::DynamicImage> {
1505 if let Ok(img) = load_image_mmap(input_path) {
1508 return Ok(img);
1509 }
1510
1511 image::open(input_path).map_err(|e| anyhow::anyhow!("Failed to load image: {}", e))
1512}
1513
1514fn load_image_mmap(input_path: &Path) -> Result<image::DynamicImage> {
1515 let file = fs::File::open(input_path)?;
1516 let file_size = file.metadata()?.len();
1517
1518 if file_size > 200 * 1024 * 1024 {
1519 let mmap = unsafe { Mmap::map(&file)? };
1520 return image::load_from_memory(&mmap)
1521 .map_err(|e| anyhow::anyhow!("Failed to decode with mmap: {}", e));
1522 }
1523
1524 drop(file);
1525 let bytes = fs::read(input_path)?;
1526 image::load_from_memory(&bytes)
1527 .map_err(|e| anyhow::anyhow!("Failed to decode from memory: {}", e))
1528}
1529
1530fn flatten_rgba8_to_rgb(img: image::RgbaImage) -> Vec<u8> {
1534 let (w, h) = img.dimensions();
1535 let mut out = Vec::with_capacity((w * h * 3) as usize);
1536 for p in img.pixels() {
1537 let [r, g, b, a] = p.0;
1538 let alpha = a as f32 / 255.0;
1539 let inv = 1.0 - alpha;
1540 out.push((r as f32 * alpha + 255.0 * inv) as u8);
1541 out.push((g as f32 * alpha + 255.0 * inv) as u8);
1542 out.push((b as f32 * alpha + 255.0 * inv) as u8);
1543 }
1544 out
1545}
1546
1547#[cfg(test)]
1548mod tests {
1549 use super::*;
1550 use std::fs;
1551
1552 fn tmp_dir(tag: &str) -> PathBuf {
1553 let d =
1554 std::env::temp_dir().join(format!("xtap_compress_test_{}_{}", tag, std::process::id()));
1555 let _ = fs::remove_dir_all(&d);
1556 fs::create_dir_all(&d).unwrap();
1557 d
1558 }
1559
1560 fn make_test_image(path: &Path, w: u32, h: u32) {
1562 let mut img = image::RgbaImage::new(w, h);
1563 for (x, y, px) in img.enumerate_pixels_mut() {
1564 let r = (x as f32 / w as f32 * 255.0) as u8;
1565 let g = (y as f32 / h as f32 * 255.0) as u8;
1566 let b = ((x + y) as f32 / (w + h) as f32 * 255.0) as u8;
1567 *px = image::Rgba([r, g, b, 255]);
1568 }
1569 img.save(path).unwrap();
1570 }
1571
1572 #[test]
1573 fn test_app_config_social_maps_to_wechat() {
1574 let cfg = AppConfig {
1576 usage_mode: "social".to_string(),
1577 custom_max_dim: 1280,
1578 custom_quality: 90,
1579 custom_target_kb: 300,
1580 ..Default::default()
1581 };
1582
1583 let pc = app_config_to_process_config(&cfg, None);
1584 assert_eq!(pc.mode, ProcessMode::WeChat);
1585 assert_eq!(pc.max_dim, 1280);
1586 assert_eq!(pc.quality, 90);
1587 assert_eq!(pc.target_kb, 300);
1588 assert_eq!(pc.subsampling, "420");
1589 let p = Processor::new(pc);
1591 let out = p.expected_output_path(Path::new("photo.jpg"));
1592 assert!(out.to_string_lossy().ends_with("_wx.jpg"));
1593 }
1594
1595 #[test]
1596 fn test_app_config_archive_no_downscale() {
1597 let cfg = AppConfig {
1599 usage_mode: "archive".to_string(),
1600 ..Default::default()
1601 };
1602
1603 let pc = app_config_to_process_config(&cfg, None);
1604 assert_eq!(pc.mode, ProcessMode::HD);
1605 assert_eq!(pc.max_dim, 0, "archive 不应缩放");
1606 assert_eq!(pc.quality, 95);
1607 assert_eq!(pc.target_kb, 0);
1608 let out = Processor::new(pc).expected_output_path(Path::new("photo.png"));
1610 assert!(out.to_string_lossy().ends_with("_hd.jpg"));
1611 }
1612
1613 #[test]
1614 fn test_process_image_compresses_and_scales() {
1615 let dir = tmp_dir("e2e");
1617 let src = dir.join("src.png");
1618 make_test_image(&src, 1600, 1200);
1619
1620 let cfg = AppConfig::default();
1621 let mut pc = app_config_to_process_config(&cfg, Some(dir.join("out")));
1622 pc.max_dim = 1280;
1623 pc.quality = 80;
1624 pc.overwrite = false;
1625 pc.keep_original_name = true;
1626
1627 let processor = Processor::new(pc);
1628 let out = processor.process_image(&src).unwrap();
1629 assert!(out.exists(), "输出文件应存在");
1630
1631 let img = image::open(&out).unwrap();
1632 assert!(
1633 img.width() <= 1280 && img.height() <= 1280,
1634 "应缩放至 1280 内,实际 {}x{}",
1635 img.width(),
1636 img.height()
1637 );
1638 assert!(
1639 fs::metadata(&out).unwrap().len() < fs::metadata(&src).unwrap().len(),
1640 "压缩后体积应小于原图"
1641 );
1642 fs::remove_dir_all(&dir).ok();
1643 }
1644
1645 #[test]
1646 fn test_expected_output_path_suffix_rules() {
1647 let base = ProcessConfig {
1649 mode: ProcessMode::Custom,
1650 max_dim: 2000,
1651 quality: 85,
1652 target_kb: 0,
1653 output_dir: None,
1654 overwrite: false,
1655 keep_original_name: false,
1656 output_format: OutputFormat::Jpeg,
1657 color_space: ColorSpace::KeepOriginal,
1658 enable_sharpening: false,
1659 sharpening_radius: 1.0,
1660 sharpening_amount: 0.8,
1661 perceptual: None,
1662 subsampling: "420".to_string(),
1663 preserve_structure: false,
1664 structure_base: None,
1665 output_suffix: None,
1666 cas_strength: 0.0,
1667 };
1668
1669 let wx = Processor::new(ProcessConfig {
1670 mode: ProcessMode::WeChat,
1671 ..base.clone()
1672 })
1673 .expected_output_path(Path::new("a.JPG"));
1674 assert!(
1675 wx.to_string_lossy().ends_with("_wx.jpg"),
1676 "大小写扩展名应归一 + 后缀 _wx,实际 {}",
1677 wx.display()
1678 );
1679
1680 let hd = Processor::new(ProcessConfig {
1681 mode: ProcessMode::HD,
1682 ..base.clone()
1683 })
1684 .expected_output_path(Path::new("a.png"));
1685 assert!(hd.to_string_lossy().ends_with("_hd.jpg"));
1687
1688 let da = Processor::new(ProcessConfig {
1689 mode: ProcessMode::Custom,
1690 ..base.clone()
1691 })
1692 .expected_output_path(Path::new("a.webp"));
1693 assert!(
1694 da.to_string_lossy().ends_with("_da.jpg"),
1695 "Custom 默认后缀 _da,实际 {}",
1696 da.display()
1697 );
1698
1699 let ow = Processor::new(ProcessConfig {
1700 overwrite: true,
1701 ..base
1702 })
1703 .expected_output_path(Path::new("b.jpg"));
1704 assert!(ow.to_string_lossy().ends_with("b.jpg"));
1705 }
1706
1707 #[test]
1708 fn test_path_self_healing_case_insensitive() {
1709 let dir = tmp_dir("heal");
1710 let real = dir.join("Photo.PNG");
1711 make_test_image(&real, 64, 64);
1712 let healed = path_self_healing(&dir.join("photo.png"));
1714 assert!(healed.exists(), "healed 路径必须存在: {}", healed.display());
1716 assert_eq!(
1717 fs::canonicalize(&healed).unwrap(),
1718 fs::canonicalize(&real).unwrap(),
1719 "healed 与真实文件应为同一文件"
1720 );
1721 fs::remove_dir_all(&dir).ok();
1722 }
1723}