Created
June 3, 2024 12:59
-
-
Save prongbang/8933c5009761d7e7f23a5ad92bb723a9 to your computer and use it in GitHub Desktop.
This file contains 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
use std::path::Path; | |
use turbojpeg::image::EncodableLayout; | |
use crate::api::convert; | |
pub async fn compress(image_path: String) -> Result<Vec<u8>, anyhow::Error> { | |
let path = Path::new(image_path.as_str()); | |
let ext = path.extension().and_then(|ext| ext.to_str()).unwrap_or(""); | |
let jpeg_data: Vec<u8>; | |
if ext != "jpg" && ext != "jpeg" { | |
// Convert the image to JPEG and collect the data into a Vec<u8> | |
jpeg_data = convert::to_jpeg(image_path)?; | |
} else { | |
jpeg_data = std::fs::read(image_path)?; | |
} | |
// decompress `jpeg_data` into an `image::RgbImage` | |
let image: turbojpeg::image::RgbImage = turbojpeg::decompress_image(&jpeg_data)?; | |
// compress `image` into JPEG with quality 95 and 2x2 chrominance subsampling | |
let jpeg_data = turbojpeg::compress_image(&image, 100, turbojpeg::Subsamp::Sub2x2)?; | |
Ok(jpeg_data.as_bytes().to_vec()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment