| 1 | use crate::error::BitMapBackendError; |
| 2 | use gif::{Encoder as GifEncoder, Frame as GifFrame, Repeat}; |
| 3 | use std::fs::File; |
| 4 | use std::path::Path; |
| 5 | |
| 6 | pub(super) struct GifFile { |
| 7 | encoder: GifEncoder<File>, |
| 8 | height: u32, |
| 9 | width: u32, |
| 10 | delay: u32, |
| 11 | } |
| 12 | |
| 13 | impl GifFile { |
| 14 | pub(super) fn new<T: AsRef<Path>>( |
| 15 | path: T, |
| 16 | dim: (u32, u32), |
| 17 | delay: u32, |
| 18 | ) -> Result<Self, BitMapBackendError> { |
| 19 | let mut encoder = GifEncoder::new( |
| 20 | File::create(path.as_ref()).map_err(BitMapBackendError::IOError)?, |
| 21 | dim.0 as u16, |
| 22 | dim.1 as u16, |
| 23 | &[], |
| 24 | ) |
| 25 | .map_err(BitMapBackendError::GifEncodingError)?; |
| 26 | |
| 27 | encoder |
| 28 | .set_repeat(Repeat::Infinite) |
| 29 | .map_err(BitMapBackendError::GifEncodingError)?; |
| 30 | |
| 31 | Ok(Self { |
| 32 | encoder, |
| 33 | width: dim.0, |
| 34 | height: dim.1, |
| 35 | delay: (delay + 5) / 10, |
| 36 | }) |
| 37 | } |
| 38 | |
| 39 | pub(super) fn flush_frame(&mut self, buffer: &[u8]) -> Result<(), BitMapBackendError> { |
| 40 | let mut frame = GifFrame::from_rgb_speed(self.width as u16, self.height as u16, buffer, 10); |
| 41 | |
| 42 | frame.delay = self.delay as u16; |
| 43 | |
| 44 | self.encoder |
| 45 | .write_frame(&frame) |
| 46 | .map_err(BitMapBackendError::GifEncodingError)?; |
| 47 | |
| 48 | Ok(()) |
| 49 | } |
| 50 | } |