neko_image/
compress.rs

1use std::io::Cursor;
2
3use image::{DynamicImage, ImageOutputFormat};
4
5pub enum ImgIndexCompression {
6  BEST = 100,
7  BETTER = 90,
8  MEDIUM = 80,
9  WORSE = 70,
10  WORST = 50
11}
12
13pub fn compute_img_size_coef(img: &DynamicImage) -> f64 {
14  let h = img.height();
15  let w = img.width();
16
17  let img_px_count = (w*h) as f64;
18  let size_megabytes = get_size_megabytes(img.as_bytes());
19  
20  let coef = img_px_count/size_megabytes;
21  coef
22}
23
24pub fn compute_img_index_compression(coef: f64) -> ImgIndexCompression {
25  match coef {
26    _ if coef > 900_000. => ImgIndexCompression::BEST,
27    _ if coef > 550_000. => ImgIndexCompression::BETTER,
28    _ if coef > 400_000. => ImgIndexCompression::MEDIUM,
29    _ if coef > 200_000. => ImgIndexCompression::WORSE,
30    _ => ImgIndexCompression::WORST,
31  }
32}
33
34pub fn get_size_megabytes(bytes: &[u8]) -> f64 {
35  bytes.len() as f64 / (1024.0 * 1024.0)
36}
37
38pub fn compress_image(image: DynamicImage, quality: Option<u8>) -> Vec<u8> {
39  let quality = match quality {
40    Some(x) => x,
41    None => 80,
42  };
43
44  let mut buf = Cursor::new(Vec::<u8>::new());
45  
46  let _ = image.write_to(&mut buf, ImageOutputFormat::Jpeg(quality));
47  let my_buf: Vec<u8> = buf.into_inner();
48  my_buf
49}