I am tring to add AVIF support using ravif
crate because it’s pure rust and no FFI needed.
However, I got error when using ravif
crate to encode image from image
crate. The encoder.encode_rgba()
function returns 1x1
pixel image object, which mismatches the
original 150x150
Here is the code
use image::*;
use ravif::*;
// some unrelated codes
// Init input and output files
let img = image::open(&self.input_path)?;
let f = File::create(&self.output_path)?;
let mut buffered_f = BufWriter::new(f);
// some unrelated codes
let (width, height) = img.dimensions();
let encoder = Encoder::new()
.with_quality(75.)
.with_speed(1);
let res = if img.color().has_alpha() { // RGBA image
let rgba = img.to_rgba8().pixels().map(|pixel| {
let [r, g, b, a] = pixel.0;
RGBA { r, g, b, a }
}).collect::<Vec<RGBA<u8>>>().first().unwrap().clone();
encoder.encode_rgba(Img::new(&[rgba], width as usize, height as usize))?
} else { // RGB image
let rgba = img.to_rgb8().pixels().map(|pixel| {
let [r, g, b] = pixel.0;
RGB { r, g, b}
}).collect::<Vec<RGB<u8>>>().first().unwrap().clone();
encoder.encode_rgb(Img::new(&[rgba], width as usize, height as usize))?
};
buffered_f.write_all(res.avif_file.as_bytes())?;
// some unrelated codes
Here is the log of unit test
buffer len 1 is less than 22500 ((150+0)x150)
stack backtrace:
0: rust_begin_unwind
1: core::panicking::panic_fmt
2: imgref::iter::PixelsRefIter<T>::new
3: imgref::Img<&[T]>::pixels
4: ravif::av1encoder::Encoder::encode_rgba
According to the backtrace. I think it is some issue about data struct converion. The original code is using image
crate to process image. I need to convert object from image
style to ravif
style correctly.
I am not an expert in Rust. I’m just tring to contribute to an opensource project.
I didn’t get any helpful hint from IDE or official docs, nor Google, even nor Claude/GPT. That is why I ask here finally – Ask real human expert. I’d be really appreciate if somebody could shed some light for me.