Created
November 15, 2024 15:05
-
-
Save TTTPOB/09ea103306bc43cea3870a243cfc22c7 to your computer and use it in GitHub Desktop.
chatgpt generated code for drag & drop to compress image file (i use it for storing receipt in quertzy). modifed for correctly running
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #![windows_subsystem = "windows"] | |
| use image::codecs::jpeg::JpegEncoder; | |
| use image::GenericImageView; | |
| use std::env; | |
| use std::fs; | |
| use std::path::{Path, PathBuf}; | |
| fn main() { | |
| // Collect arguments passed to the executable (paths of the dropped files) | |
| let args: Vec<String> = env::args().skip(1).collect(); | |
| if args.is_empty() { | |
| eprintln!("No files provided. Drag and drop image files onto this executable."); | |
| return; | |
| } | |
| for file_path in args { | |
| let path = Path::new(&file_path); | |
| // Ensure the file exists and is readable | |
| if !path.exists() { | |
| eprintln!("File does not exist: {:?}", path); | |
| continue; | |
| } | |
| match compress_image(path) { | |
| Ok(_) => println!("Successfully processed: {:?}", path), | |
| Err(err) => eprintln!("Error processing {:?}: {}", path, err), | |
| } | |
| } | |
| } | |
| fn compress_image(path: &Path) -> Result<(), Box<dyn std::error::Error>> { | |
| // Open the image | |
| let img = image::open(path)?; | |
| // Get original dimensions | |
| let (orig_width, orig_height) = img.dimensions(); | |
| // Resize the image to half its dimensions | |
| let resized_img = img.resize( | |
| orig_width / 2, | |
| orig_height / 2, | |
| image::imageops::FilterType::Lanczos3, | |
| ); | |
| // Create the output path | |
| let output_path = create_output_path(path)?; | |
| // below code did compress and write. note encoder.encode_image actually | |
| // writes the image to the file as the file handle is passed when init | |
| // encoder | |
| let mut output_handle = fs::File::create(output_path)?; | |
| let mut encoder = JpegEncoder::new_with_quality(&mut output_handle, 75); | |
| encoder.encode_image(&resized_img)?; | |
| Ok(()) | |
| } | |
| fn create_output_path(input_path: &Path) -> Result<PathBuf, Box<dyn std::error::Error>> { | |
| // Get the directory and file name | |
| let dir = input_path | |
| .parent() | |
| .ok_or("Cannot determine the parent directory")?; | |
| let file_stem = input_path | |
| .file_stem() | |
| .ok_or("Cannot determine the file stem")?; | |
| let new_file_name = format!("{}_compressed.jpg", file_stem.to_string_lossy()); | |
| let output_path = dir.join(new_file_name); | |
| Ok(output_path) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment