diff options
author | metamuffin <metamuffin@disroot.org> | 2023-08-06 13:52:09 +0200 |
---|---|---|
committer | metamuffin <metamuffin@disroot.org> | 2023-08-06 13:52:09 +0200 |
commit | c3c4734beb7b9650936b3c74df21d72a597cd94c (patch) | |
tree | 3728d62a70cfc65231beac41ae62f0da4d971308 /transcoder/src/image.rs | |
parent | 8551bf2e34d9543fa41a83fae785ed81d6a6c10f (diff) | |
download | jellything-c3c4734beb7b9650936b3c74df21d72a597cd94c.tar jellything-c3c4734beb7b9650936b3c74df21d72a597cd94c.tar.bz2 jellything-c3c4734beb7b9650936b3c74df21d72a597cd94c.tar.zst |
transcode images
Diffstat (limited to 'transcoder/src/image.rs')
-rw-r--r-- | transcoder/src/image.rs | 46 |
1 files changed, 46 insertions, 0 deletions
diff --git a/transcoder/src/image.rs b/transcoder/src/image.rs new file mode 100644 index 0000000..d721e7b --- /dev/null +++ b/transcoder/src/image.rs @@ -0,0 +1,46 @@ +use jellybase::{cache_file, AssetLocationExt}; +use jellycommon::AssetLocation; +use log::info; +use rgb::FromSlice; +use std::{ + fs::File, + io::{BufReader, Write}, + path::PathBuf, +}; + +pub fn transcode( + asset: AssetLocation, + quality: f32, + speed: u8, + width: usize, +) -> anyhow::Result<PathBuf> { + let original_path = asset.path(); + let path = cache_file(&[ + original_path.as_os_str().to_str().unwrap(), + &format!("{width} {quality} {speed}"), + ]); + if !path.exists() { + info!("encoding {path:?} (speed={speed}, quality={quality}, width={width})"); + let reader = image::io::Reader::new(BufReader::new(File::open(original_path)?)) + .with_guessed_format()?; + let original = reader.decode()?.to_rgba8(); + let image = image::imageops::resize( + &original, + width as u32, + width as u32 * original.height() / original.width(), + image::imageops::FilterType::Lanczos3, + ); + let pixels = image.to_vec(); + let encoded = ravif::Encoder::new() + .with_speed(speed.clamp(1, 10)) + .with_quality(quality.clamp(1., 100.)) + .encode_rgba(ravif::Img::new( + pixels.as_rgba(), + image.width() as usize, + image.height() as usize, + ))?; + info!("writing to cache: {path:?}"); + File::create(&path)?.write_all(&encoded.avif_file)?; + } + Ok(path) +} |