Converta qualquer imagem para o formato WebP.
Solicite ao usuário a taxa de compressão (qualidade).
Peça o tamanho desejado da imagem.
Pergunte se o usuário deseja manter a mesma proporção da imagem original.
Assistant
Sure! Below is a Rust program that fulfills your requirements:
Converts any image to the WebP format.
Asks the user for the compression rate (quality).
Asks for the desired size of the image.
Asks if the user wants to keep the same proportion as the original image.
To run this program, you'll need to add dependencies to your Cargo.toml file.
toml
[dependencies]
image = { version = "0.24", features = ["webp", "png", "jpeg"] }
Now, here's the Rust code:
rust
use image::imageops::FilterType;
use image::{DynamicImage, GenericImageView, ImageFormat};
use std::io::{self, Write};
use std::path::Path;
fn main() {
// Ask the user for the image path
println!("Enter the path to the image:");
let image_path = read_input();
// Load the image
let img = match image::open(&image_path) {
Ok(img) => img,
Err(e) => {
eprintln!("Failed to open image: {}", e);
return;
}
};
// Ask for the compression quality (0-100)
println!("Enter the compression quality (0-100):");
let quality_input = read_input();
let quality: u8 = match quality_input.trim().parse() {
Ok(q) if q <= 100 => q,
_ => {
eprintln!("Invalid quality value. Must be between 0 and 100.");
return;
}
};
// Get the current dimensions
let (orig_width, orig_height) = img.dimensions();
// Ask for desired size
println!("Enter the desired width:");
let width_input = read_input();
let desired_width: u32 = match width_input.trim().parse() {
Ok(w) if w > 0 => w,
_ => {
eprintln!("Invalid width value.");
return;
}
};
println!("Enter the desired height:");
let height_input = read_input();
let desired_height: u32 = match height_input.trim().parse() {
Ok(h) if h > 0 => h,
_ => {
eprintln!("Invalid height value.");
return;
}
};
// Ask if the user wants to maintain aspect ratio
println!("Maintain aspect ratio? (y/n):");
let aspect_ratio_input = read_input();
let maintain_aspect_ratio = matches!(
aspect_ratio_input.trim().to_lowercase().as_str(),
"y" | "yes"
);
// Resize the image
let resized_img = if maintain_aspect_ratio {
// Calculate the scaling factor
let scale_width = desired_width as f32 / orig_width as f32;
let scale_height = desired_height as f32 / orig_height as f32;
let scale = scale_width.min(scale_height);
let new_width = (orig_width as f32 * scale) as u32;
let new_height = (orig_height as f32 * scale) as u32;
img.resize(new_width, new_height, FilterType::Lanczos3)
} else {
img.resize_exact(desired_width, desired_height, FilterType::Lanczos3)
};
// Get the output file path
let output_path = get_output_path(&image_path);
// Save the image as WebP
match save_webp(&resized_img, &output_path, quality) {
Ok(_) => println!("Image saved to {}", output_path),
Err(e) => eprintln!("Failed to save image: {}", e),
}
}
fn read_input() -> String {
let mut input = String::new();
print!("> ");
// Flush stdout to ensure the prompt is displayed
io::stdout().flush().unwrap();
io::stdin().read_line(&mut input).expect("Failed to read input");
input
}
fn get_output_path(input_path: &str) -> String {
let path = Path::new(input_path);
let stem = match path.file_stem() {
Some(name) => name.to_string_lossy(),
None => "output".into(),
};
let output_file = format!("{}_converted.webp", stem);
output_file
}
fn save_webp(img: &DynamicImage, output_path: &str, quality: u8) -> image::ImageResult<()> {
let mut output_file = std::fs::File::create(output_path)?;
let encoder = image::codecs::webp::WebPEncoder::new_with_quality(&mut output_file, quality);
encoder.encode_image(img)
}
Explanation:
Dependencies:
image: A powerful image processing library in Rust that supports various image formats, including WebP.
Program Flow:
User Input:
The program prompts the user for the image path, compression quality, desired dimensions, and whether to maintain the aspect ratio.
Image Loading:
It attempts to load the image from the provided path.
Image Resizing:
Depending on the user's choice, it resizes the image while maintaining the aspect ratio or stretches it to the desired dimensions.
Image Saving:
The program saves the processed image in WebP format with the specified quality.
Functions:
read_input(): Reads a line of input from the user.
get_output_path(): Generates an output file path based on the input file name.
save_webp(): Saves the image in WebP format with the specified quality.
How to Run the Program:
Setup a New Cargo Project:
Open your terminal and run:
bash
cargo new image_converter
cd image_converter
Add Dependencies:
Edit your Cargo.toml file to include:
toml
[dependencies]
image = { version = "0.24", features = ["webp", "png", "jpeg"] }
Replace main.rs:
Replace the contents of src/main.rs with the provided code.
Build and Run:
bash
cargo run
Follow the Prompts:
The program will prompt you for the necessary inputs. Provide them accordingly.
Example Run:
code
Enter the path to the image:
> path/to/your/image.jpg
Enter the compression quality (0-100):
> 80
Enter the desired width:
> 800
Enter the desired height:
> 600
Maintain aspect ratio? (y/n):
> y
Image saved to image_converted.webp
Notes:
The program supports input images in formats supported by the image crate (e.g., JPEG, PNG, etc.).
The output image will be saved in the same directory with a filename like yourimage_converted.webp.
Ensure that the image paths you provide are correct and that you have the necessary read/write permissions.
Feel free to ask if you have any questions or need further assistance!