1#[cfg(feature = "fun")]
2pub mod fun;
3#[cfg(feature = "imageops")]
4pub mod imageops;
5#[cfg(feature = "jobs")]
6pub mod jobs;
7#[cfg(feature = "osu")]
8pub mod osu;
9#[cfg(feature = "tetrio")]
10pub mod tetrio;
11
12pub type Error = Box<dyn std::error::Error + Send + Sync>;
13#[derive(Debug, Clone, Copy)]
14pub struct AverageColor {
16 red: u8,
17 green: u8,
18 blue: u8,
19}
20impl AverageColor {
21 #[cfg(feature = "discord")]
22 pub fn to_embed_color(&self) -> serenity::all::Color {
23 serenity::all::Color::from_rgb(self.red, self.green, self.blue)
24 }
25
26 pub fn new(red: u8, green: u8, blue: u8) -> Self {
27 Self { red, green, blue }
28 }
29
30 pub async fn from_image_url(url: &str) -> Result<AverageColor, Error> {
31 use image::{GenericImageView, load_from_memory};
32 let image_bytes = &reqwest::get(url).await?.bytes().await?;
33
34 let image = load_from_memory(image_bytes)?;
35 let (width, height) = image.dimensions();
36 let mut red = 0u64;
37 let mut green = 0u64;
38 let mut blue = 0u64;
39
40 for x in 0..width {
42 for y in 0..height {
43 let pixel = image.get_pixel(x, y).0; red += pixel[0] as u64;
45 green += pixel[1] as u64;
46 blue += pixel[2] as u64;
47 }
48 }
49
50 let num_pixels = (width * height) as u64;
52 red /= num_pixels;
53 green /= num_pixels;
54 blue /= num_pixels;
55
56 Ok(AverageColor::new(red as u8, green as u8, blue as u8))
57 }
58
59 pub async fn from_bytes(image_bytes: Vec<u8>) -> Result<AverageColor, Error> {
60 use image::{GenericImageView, load_from_memory};
61 let image = load_from_memory(&image_bytes)?;
62 let (width, height) = image.dimensions();
63 let mut red = 0u64;
64 let mut green = 0u64;
65 let mut blue = 0u64;
66
67 for x in 0..width {
69 for y in 0..height {
70 let pixel = image.get_pixel(x, y).0; red += pixel[0] as u64;
72 green += pixel[1] as u64;
73 blue += pixel[2] as u64;
74 }
75 }
76
77 let num_pixels = (width * height) as u64;
79 red /= num_pixels;
80 green /= num_pixels;
81 blue /= num_pixels;
82
83 Ok(AverageColor::new(red as u8, green as u8, blue as u8))
84 }
85}