Skip to content

Commit

Permalink
Expose DecodedImage in the public API (#65)
Browse files Browse the repository at this point in the history
* Expose DecodedImage in the public API

* Add `DecodedImage::from_raw` constructor
  • Loading branch information
calebfletcher authored Apr 2, 2024
1 parent 59326e5 commit 2d3da60
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 9 deletions.
4 changes: 1 addition & 3 deletions galileo/src/control/event_processor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -198,9 +198,7 @@ impl EventProcessor {
None
}
RawUserEvent::TouchMove(touch) => {
let Some(touch_info) = self.touches.iter().find(|t| t.id == touch.touch_id) else {
return None;
};
let touch_info = self.touches.iter().find(|t| t.id == touch.touch_id)?;
let position = touch.position;

let mut events = vec![];
Expand Down
38 changes: 33 additions & 5 deletions galileo/src/decoded_image.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,22 @@
//! This module contains utilities for loading images to be rendered on the map.

#[cfg(not(target_arch = "wasm32"))]
use crate::error::GalileoError;
#[cfg(not(target_arch = "wasm32"))]
use std::ops::Deref;

/// An image that has been loaded into memory.
#[derive(Debug, Clone)]
pub struct DecodedImage {
pub bytes: Vec<u8>,
pub dimensions: (u32, u32),
/// Raw bytes of the image, in RGBA order.
pub(crate) bytes: Vec<u8>,
/// Width and height of the image.
pub(crate) dimensions: (u32, u32),
}

impl DecodedImage {
/// Decode an image from a byte slice.
///
/// Attempts to guess the format of the image from the data. Non-RGBA images
/// will be converted to RGBA.
#[cfg(not(target_arch = "wasm32"))]
pub fn new(bytes: &[u8]) -> Result<Self, GalileoError> {
use image::GenericImageView;
Expand All @@ -18,8 +25,29 @@ impl DecodedImage {
let dimensions = decoded.dimensions();

Ok(Self {
bytes: Vec::from(bytes.deref()),
bytes: bytes.into_vec(),
dimensions,
})
}

/// Create a DecodedImage from a buffer of raw RGBA pixels.
#[cfg(not(target_arch = "wasm32"))]
pub fn from_raw(
bytes: impl Into<Vec<u8>>,
width: u32,
height: u32,
) -> Result<Self, GalileoError> {
let bytes = bytes.into();

if bytes.len() != 4 * width as usize * height as usize {
return Err(GalileoError::Generic(
"invalid image dimensions for buffer size".into(),
));
}

Ok(Self {
bytes,
dimensions: (width, height),
})
}
}
2 changes: 1 addition & 1 deletion galileo/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@
pub(crate) mod async_runtime;
mod color;
pub mod control;
pub(crate) mod decoded_image;
pub mod decoded_image;
pub mod error;
pub mod layer;
mod lod;
Expand Down

0 comments on commit 2d3da60

Please sign in to comment.