1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
use std::path::Path;
use image::ImageError::{IoError, Unsupported};
use image::{DynamicImage, RgbImage, RgbaImage};
use crate::image::errors::ImageError;
use crate::image::ImageError::InvalidParameter;
/// ImageData represents the raw data of an image.
#[derive(Debug)]
pub struct ImageData {
width: u32,
height: u32,
data: Vec<u8>,
}
impl ImageData {
/// Creates a new `ImageData` instance with the given width, height, and pixels.
///
/// # Arguments
/// * `width` - The width of the image data.
/// * `height` - The height of the image data.
/// * `data` - The raw data of the image data. The data is in RGBA format.
///
/// # Returns
/// A new `ImageData` instance.
///
/// # Errors
/// Returns an error if the length of the pixels is not a multiple of the width and height.
///
/// # Examples
/// ```
/// use auto_palette::ImageData;
///
/// let image_data = ImageData::new(1, 2, vec![0, 0, 0, 255, 255, 255, 255, 255]).unwrap();
/// assert_eq!(image_data.width(), 1);
/// assert_eq!(image_data.height(), 2);
/// assert_eq!(image_data.data(), &[0, 0, 0, 255, 255, 255, 255, 255]);
/// ```
pub fn new(width: u32, height: u32, data: Vec<u8>) -> Result<Self, ImageError> {
if data.len() != ((width * height * 4) as usize) {
return Err(InvalidParameter);
}
Ok(Self {
width,
height,
data,
})
}
/// Loads an image data from the given path.
///
/// # Arguments
/// * `path` - The path to the image file.
///
/// # Returns
/// The result of the image data.
///
/// # Errors
/// Returns an error if the image file is not supported or an I/O error occurred.
///
/// # Examples
/// ```
/// use auto_palette::ImageData;
///
/// let image_data = ImageData::load("./tests/assets/holly-booth-hLZWGXy5akM-unsplash.jpg").unwrap();
/// assert_eq!(image_data.width(), 480);
/// assert_eq!(image_data.height(), 722);
/// assert_eq!(image_data.data().len(), 1_386_240);
/// ```
pub fn load<P>(path: P) -> Result<Self, ImageError>
where
P: AsRef<Path>,
{
let image = image::open(&path).map_err(|error| match error {
Unsupported(error) => ImageError::UnsupportedFile(error),
IoError(error) => ImageError::IoError(error),
error => ImageError::Unknown(error),
})?;
Self::try_from(&image)
}
/// Returns whether the image data is empty.
///
/// # Returns
/// `true` if the image data is empty; otherwise, `false`.
#[must_use]
pub fn is_empty(&self) -> bool {
self.data.is_empty()
}
/// Returns the width of the image data.
///
/// # Returns
/// The width of the image data.
#[must_use]
pub fn width(&self) -> u32 {
self.width
}
/// Returns the height of the image data.
///
/// # Returns
/// The height of the image data.
#[must_use]
pub fn height(&self) -> u32 {
self.height
}
/// Returns the raw data of the image data.
///
/// # Returns
/// The raw data of the image data. The data is in RGBA format.
#[must_use]
pub fn data(&self) -> &[u8] {
&self.data
}
}
impl TryFrom<&DynamicImage> for ImageData {
type Error = ImageError;
fn try_from(image: &DynamicImage) -> Result<Self, Self::Error> {
match image {
DynamicImage::ImageRgb8(image) => Ok(Self::from(image)),
DynamicImage::ImageRgba8(image) => Ok(Self::from(image)),
_ => Err(ImageError::UnsupportedType(image.color())),
}
}
}
impl From<&RgbImage> for ImageData {
fn from(image: &RgbImage) -> Self {
let (width, height) = image.dimensions();
let size = (width * height) as usize;
let data = image
.pixels()
.fold(Vec::with_capacity(size * 4), |mut pixels, pixel| {
pixels.extend_from_slice(&[pixel[0], pixel[1], pixel[2], 255]);
pixels
});
Self {
width,
height,
data,
}
}
}
impl From<&RgbaImage> for ImageData {
fn from(image: &RgbaImage) -> Self {
let (width, height) = image.dimensions();
let data = image.to_vec();
Self {
width,
height,
data,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_new_image_data() {
// Act
let pixels = vec![
0, 0, 0, 255, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255,
];
let image_data = ImageData::new(2, 2, pixels.clone()).unwrap();
// Assert
assert!(!image_data.is_empty());
assert_eq!(image_data.width(), 2);
assert_eq!(image_data.height(), 2);
assert_eq!(image_data.data(), &pixels);
}
#[test]
fn test_new_empty_image_data() {
// Act
let pixels = vec![];
let image_data = ImageData::new(0, 0, pixels.clone()).unwrap();
// Assert
assert!(image_data.is_empty());
assert_eq!(image_data.width(), 0);
assert_eq!(image_data.height(), 0);
assert_eq!(image_data.data(), &pixels);
}
#[test]
fn test_new_with_invalid_parameters() {
// Act
let image_data = ImageData::new(2, 2, vec![0, 0, 0, 255, 255, 255, 255]);
// Assert
assert!(image_data.is_err());
}
#[test]
fn test_load() {
// Act
let image_data =
ImageData::load("./tests/assets/holly-booth-hLZWGXy5akM-unsplash.jpg").unwrap();
// Assert
assert!(!image_data.is_empty());
assert_eq!(image_data.width(), 480);
assert_eq!(image_data.height(), 722);
assert_eq!(image_data.data().len(), 480 * 722 * 4);
}
#[test]
fn test_load_with_rgba_image() {
// Act
let image_data = ImageData::load("./tests/assets/flags/np.png").unwrap();
// Assert
assert!(!image_data.is_empty());
assert_eq!(image_data.width(), 197);
assert_eq!(image_data.height(), 240);
assert_eq!(image_data.data().len(), 197 * 240 * 4);
}
#[test]
fn test_load_with_invalid_path() {
// Act
let image_data = ImageData::load("./tests/assets/invalid.jpg");
// Assert
assert!(image_data.is_err());
}
#[test]
fn test_load_with_invalid_file() {
// Act
let image_data = ImageData::load("../../tests/assets/empty.txt");
// Assert
assert!(image_data.is_err());
}
}