forge
Explore
Log in

Don't you dare go Hollow

yumush

Clone
★ 0

0 watching0 forksRustAGPL-3.06.8 MiB27ceb05Tahinli8 hours ago399 commits

avatar.rs62 lines, 1.6 KiBHistoryRawDownload
1use crate::net::Fail;
2use common::{
3 constant::AVATAR_SIZE,
4 error::{Error, Field, Problem},
5};
6use image::{DynamicImage, RgbImage, codecs::jpeg::JpegEncoder, imageops::FilterType};
7
8const QUALITIES: [u8; 2] = [85, 60];
9const SIDES: [u32; 4] = [
10 AVATAR_SIZE,
11 AVATAR_SIZE * 3 / 4,
12 AVATAR_SIZE / 2,
13 AVATAR_SIZE / 4,
14];
15
16pub fn prepare(bytes: &[u8], maximum: u64) -> Result<Vec<u8>, Fail> {
17 let image = center_square(image::load_from_memory(bytes).map_err(image_error)?);
18
19 let mut encoded = Vec::new();
20 for side in SIDES {
21 let square = image
22 .resize_exact(side, side, FilterType::Lanczos3)
23 .to_rgb8();
24 for quality in QUALITIES {
25 encoded = encode(&square, quality)?;
26 if encoded.len() as u64 <= maximum {
27 return Ok(encoded);
28 }
29 }
30 }
31
32 Err(Error::Invalid {
33 field: Field::Avatar,
34 problem: Problem::Length {
35 min: 0,
36 max: maximum,
37 actual: encoded.len() as u64,
38 },
39 }
40 .into())
41}
42
43fn center_square(image: DynamicImage) -> DynamicImage {
44 let side = image.width().min(image.height());
45 let x = (image.width() - side) / 2;
46 let y = (image.height() - side) / 2;
47
48 image.crop_imm(x, y, side, side)
49}
50
51fn encode(image: &RgbImage, quality: u8) -> Result<Vec<u8>, Fail> {
52 let mut bytes = Vec::new();
53 JpegEncoder::new_with_quality(&mut bytes, quality)
54 .encode_image(image)
55 .map_err(image_error)?;
56
57 Ok(bytes)
58}
59
60fn image_error(error: image::ImageError) -> Fail {
61 Fail::Io(error.to_string())
62}