From ad1dbee5fd74cf1010f6c0b27cedfb0c7d826156 Mon Sep 17 00:00:00 2001 From: gered Date: Thu, 30 Mar 2023 17:56:40 -0400 Subject: [PATCH] add RgbaBitmap::from_bytes with some limited pixel format support --- ggdt/src/graphics/bitmap/mod.rs | 3 +++ ggdt/src/graphics/bitmap/rgb/mod.rs | 37 ++++++++++++++++++++++++++++- 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/ggdt/src/graphics/bitmap/mod.rs b/ggdt/src/graphics/bitmap/mod.rs index 37284b1..0d43160 100644 --- a/ggdt/src/graphics/bitmap/mod.rs +++ b/ggdt/src/graphics/bitmap/mod.rs @@ -24,6 +24,9 @@ pub enum BitmapError { #[error("Unknown bitmap file type: {0}")] UnknownFileType(String), + #[error("Bitmap I/O error")] + IOError(#[from] std::io::Error), + #[error("Bitmap IFF file error")] IffError(#[from] iff::IffError), diff --git a/ggdt/src/graphics/bitmap/rgb/mod.rs b/ggdt/src/graphics/bitmap/rgb/mod.rs index 1bb0427..e980cf4 100644 --- a/ggdt/src/graphics/bitmap/rgb/mod.rs +++ b/ggdt/src/graphics/bitmap/rgb/mod.rs @@ -1,7 +1,8 @@ +use byteorder::ReadBytesExt; use std::path::Path; use crate::graphics::bitmap::{Bitmap, BitmapError}; -use crate::graphics::color::to_rgb32; +use crate::graphics::color::{to_argb32, to_rgb32}; use crate::graphics::palette::Palette; pub mod blit; @@ -9,6 +10,12 @@ pub mod primitives; pub type RgbaBitmap = Bitmap; +#[derive(Debug, Copy, Clone, Eq, PartialEq)] +pub enum RgbaPixelFormat { + ARGB, + RGBA, +} + impl RgbaBitmap { /// Creates a new Bitmap with the specified dimensions. /// @@ -22,6 +29,34 @@ impl RgbaBitmap { Self::internal_new(width, height, to_rgb32(0, 0, 0)) } + pub fn from_bytes( + width: u32, + height: u32, + format: RgbaPixelFormat, + reader: &mut T, + ) -> Result { + let mut bitmap = Self::internal_new(width, height, 0)?; + for pixel in bitmap.pixels_mut().iter_mut() { + *pixel = match format { + RgbaPixelFormat::RGBA => { + let r = reader.read_u8()?; + let g = reader.read_u8()?; + let b = reader.read_u8()?; + let a = reader.read_u8()?; + to_argb32(a, r, g, b) + } + RgbaPixelFormat::ARGB => { + let a = reader.read_u8()?; + let r = reader.read_u8()?; + let g = reader.read_u8()?; + let b = reader.read_u8()?; + to_argb32(a, r, g, b) + } + }; + } + Ok(bitmap) + } + pub fn load_file(path: &Path) -> Result<(Self, Option), BitmapError> { if let Some(extension) = path.extension() { let extension = extension.to_ascii_lowercase();