Skip to content

Commit

Permalink
feat(backend): convert uploaded images to webp (#426)
Browse files Browse the repository at this point in the history
zax-xyz authored May 13, 2023
1 parent 7951dd8 commit 8cb072d
Showing 5 changed files with 40 additions and 7 deletions.
32 changes: 32 additions & 0 deletions backend/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions backend/server/Cargo.toml
Original file line number Diff line number Diff line change
@@ -33,6 +33,7 @@ diesel_migrations = "1.4.0"
figment = { version = "0.10", features = ["env", "toml", "json"] }
image = "0.24.4"
strum = { version = "0.24", features = ["derive"] }
webp = "0.2"

[dependencies.uuid]
version = "1.2.2"
2 changes: 1 addition & 1 deletion backend/server/src/campaigns.rs
Original file line number Diff line number Diff line change
@@ -280,7 +280,7 @@ pub async fn set_cover_image(
let old_logo_uuid = db
.run(move |conn| Campaign::get_cover_image(&conn, campaign_id))
.await;
let logo_uuid = Uuid::new_v4().as_hyphenated().to_string();
let logo_uuid = Uuid::new_v4().as_hyphenated().to_string() + ".webp";

let image = try_decode_data(image).await.or_else(|_| {
Err(JsonErr(
10 changes: 5 additions & 5 deletions backend/server/src/images.rs
Original file line number Diff line number Diff line change
@@ -6,6 +6,7 @@ use std::{
path::{Path, PathBuf},
};
use strum::{EnumIter, IntoEnumIterator};
use webp::Encoder;

pub enum ImageDecodeError {
ImageError(ImageError),
@@ -56,18 +57,17 @@ pub fn save_image(
image: DynamicImage,
location: ImageLocation,
image_uuid: &str,
) -> Result<PathBuf, ImageError> {
) -> std::io::Result<PathBuf> {
ImageLocation::iter().for_each(|location| {
fs::create_dir_all(Path::new(IMAGE_BASE_PATH).join(image_location_to_string(location)))
.ok();
});

let path = get_image_path(location, image_uuid);

match image.save_with_format(&path, image::ImageFormat::Png) {
Ok(_) => Ok(path),
Err(e) => Err(e),
}
let encoder = Encoder::from_image(&image).unwrap();
let webp = encoder.encode(80.0);
std::fs::write(&path, &*webp).map(|_| path)
}

pub fn get_image_path(location: ImageLocation, image_uuid: &str) -> PathBuf {
2 changes: 1 addition & 1 deletion backend/server/src/organisation.rs
Original file line number Diff line number Diff line change
@@ -159,7 +159,7 @@ pub async fn set_logo(
let old_logo_uuid = db
.run(move |conn| Organisation::get_logo(&conn, org_id))
.await;
let logo_uuid = Uuid::new_v4().as_hyphenated().to_string();
let logo_uuid = Uuid::new_v4().as_hyphenated().to_string() + ".webp";

let image = try_decode_data(image).await.or_else(|_| {
Err(JsonErr(

0 comments on commit 8cb072d

Please sign in to comment.