add: lossy encode webp images
This commit is contained in:
parent
03480d32db
commit
24162573ee
8 changed files with 145 additions and 437 deletions
|
@ -57,31 +57,6 @@ where
|
|||
}
|
||||
}
|
||||
|
||||
/// Create an image buffer given an input of `bytes`
|
||||
pub fn save_buffer(path: &str, bytes: Vec<u8>, format: image::ImageFormat) -> std::io::Result<()> {
|
||||
let pre_img_buffer = match image::load_from_memory(&bytes) {
|
||||
Ok(i) => i,
|
||||
Err(_) => {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidData,
|
||||
"Image failed",
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
let file = File::create(path)?;
|
||||
let mut writer = BufWriter::new(file);
|
||||
|
||||
if pre_img_buffer.write_to(&mut writer, format).is_err() {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::Other,
|
||||
"Image conversion failed",
|
||||
));
|
||||
};
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A file extractor accepting:
|
||||
/// * `multipart/form-data`
|
||||
///
|
||||
|
@ -163,3 +138,64 @@ where
|
|||
Ok(Self(body, json))
|
||||
}
|
||||
}
|
||||
|
||||
/// Create an image buffer given an input of `bytes`.
|
||||
pub fn save_buffer(path: &str, bytes: Vec<u8>, format: image::ImageFormat) -> std::io::Result<()> {
|
||||
let pre_img_buffer = match image::load_from_memory(&bytes) {
|
||||
Ok(i) => i,
|
||||
Err(_) => {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidData,
|
||||
"Image failed",
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
let file = File::create(path)?;
|
||||
let mut writer = BufWriter::new(file);
|
||||
|
||||
if pre_img_buffer.write_to(&mut writer, format).is_err() {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::Other,
|
||||
"Image conversion failed",
|
||||
));
|
||||
};
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
const WEBP_ENCODE_QUALITY: f32 = 85.0;
|
||||
|
||||
/// Create a WEBP image buffer given an input of `bytes`.
|
||||
pub fn save_webp_buffer(path: &str, bytes: Vec<u8>) -> std::io::Result<()> {
|
||||
let img = match image::load_from_memory(&bytes) {
|
||||
Ok(i) => i,
|
||||
Err(_) => {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidData,
|
||||
"Image failed",
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
let encoder = match webp::Encoder::from_image(&img) {
|
||||
Ok(e) => e,
|
||||
Err(e) => {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::Other,
|
||||
e.to_string(),
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
let mem = encoder.encode(WEBP_ENCODE_QUALITY);
|
||||
|
||||
if std::fs::write(path, &*mem).is_err() {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::Other,
|
||||
"Image conversion failed",
|
||||
));
|
||||
};
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue