| 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 | #![forbid(unsafe_code)] |
| 36 | #![warn(missing_docs)] |
| 37 | |
| 38 | use std::fmt; |
| 39 | use std::path::Path; |
| 40 | |
| 41 | #[cfg(feature = "gpui")] |
| 42 | pub mod gpui; |
| 43 | |
| 44 | |
| 45 | #[cfg(feature = "gpui")] |
| 46 | pub use gpui::{ |
| 47 | AnimationDecoder, Delay, Frame, Frames, ImageDecoder, codecs, guess_format, |
| 48 | load_from_memory_with_format, |
| 49 | }; |
| 50 | |
| 51 | |
| 52 | #[cfg(feature = "gpui")] |
| 53 | pub type ImageBuffer = RgbaImage; |
| 54 | |
| 55 | |
| 56 | #[derive(Debug)] |
| 57 | pub enum ImageError { |
| 58 | |
| 59 | Decoding(String), |
| 60 | |
| 61 | Unsupported(String), |
| 62 | |
| 63 | IoError(std::io::Error), |
| 64 | } |
| 65 | |
| 66 | impl fmt::Display for ImageError { |
| 67 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 68 | match self { |
| 69 | ImageError::Decoding(m) => write!(f, "Format error decoding image: {m}"), |
| 70 | ImageError::Unsupported(m) => write!(f, "The image format is not supported: {m}"), |
| 71 | ImageError::IoError(e) => write!(f, "{e}"), |
| 72 | } |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | impl std::error::Error for ImageError { |
| 77 | fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { |
| 78 | match self { |
| 79 | ImageError::IoError(e) => Some(e), |
| 80 | _ => None, |
| 81 | } |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | impl From<std::io::Error> for ImageError { |
| 86 | fn from(e: std::io::Error) -> ImageError { |
| 87 | ImageError::IoError(e) |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | impl From<ec_image::Error> for ImageError { |
| 92 | fn from(e: ec_image::Error) -> ImageError { |
| 93 | match e { |
| 94 | ec_image::Error::Io(e) => ImageError::IoError(e), |
| 95 | ec_image::Error::Unsupported { what, why } => { |
| 96 | ImageError::Unsupported(format!("{what}: {why}")) |
| 97 | } |
| 98 | other => ImageError::Decoding(other.to_string()), |
| 99 | } |
| 100 | } |
| 101 | } |
| 102 | |
| 103 | |
| 104 | pub type ImageResult<T> = Result<T, ImageError>; |
| 105 | |
| 106 | |
| 107 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 108 | pub enum ImageFormat { |
| 109 | |
| 110 | Png, |
| 111 | |
| 112 | Jpeg, |
| 113 | |
| 114 | WebP, |
| 115 | |
| 116 | #[cfg(feature = "gpui")] |
| 117 | Gif, |
| 118 | |
| 119 | #[cfg(feature = "gpui")] |
| 120 | Bmp, |
| 121 | |
| 122 | #[cfg(feature = "gpui")] |
| 123 | Tiff, |
| 124 | } |
| 125 | |
| 126 | |
| 127 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 128 | pub struct Luma(pub [u8; 1]); |
| 129 | |
| 130 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 131 | pub struct Rgb(pub [u8; 3]); |
| 132 | |
| 133 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 134 | pub struct Rgba(pub [u8; 4]); |
| 135 | |
| 136 | |
| 137 | |
| 138 | |
| 139 | macro_rules! buffer { |
| 140 | ($name:ident, $pixel:ident, $channels:expr, $doc:literal) => { |
| 141 | #[doc = $doc] |
| 142 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 143 | pub struct $name { |
| 144 | width: u32, |
| 145 | height: u32, |
| 146 | data: Vec<u8>, |
| 147 | } |
| 148 | |
| 149 | impl $name { |
| 150 | |
| 151 | #[doc = concat!(stringify!($channels), " bytes per pixel.")] |
| 152 | pub fn from_raw(width: u32, height: u32, data: Vec<u8>) -> Option<$name> { |
| 153 | let needed = (width as usize) |
| 154 | .checked_mul(height as usize)? |
| 155 | .checked_mul($channels)?; |
| 156 | (data.len() >= needed).then_some($name { |
| 157 | width, |
| 158 | height, |
| 159 | data, |
| 160 | }) |
| 161 | } |
| 162 | |
| 163 | |
| 164 | pub fn dimensions(&self) -> (u32, u32) { |
| 165 | (self.width, self.height) |
| 166 | } |
| 167 | |
| 168 | |
| 169 | pub fn width(&self) -> u32 { |
| 170 | self.width |
| 171 | } |
| 172 | |
| 173 | |
| 174 | pub fn height(&self) -> u32 { |
| 175 | self.height |
| 176 | } |
| 177 | |
| 178 | |
| 179 | |
| 180 | pub fn get_pixel(&self, x: u32, y: u32) -> $pixel { |
| 181 | assert!( |
| 182 | x < self.width && y < self.height, |
| 183 | "({x}, {y}) is outside a {}x{} image", |
| 184 | self.width, |
| 185 | self.height |
| 186 | ); |
| 187 | let at = ((y as usize) * (self.width as usize) + x as usize) * $channels; |
| 188 | let mut pixel = [0u8; $channels]; |
| 189 | pixel.copy_from_slice(&self.data[at..at + $channels]); |
| 190 | $pixel(pixel) |
| 191 | } |
| 192 | |
| 193 | |
| 194 | pub fn as_raw(&self) -> &Vec<u8> { |
| 195 | &self.data |
| 196 | } |
| 197 | |
| 198 | |
| 199 | pub fn into_raw(self) -> Vec<u8> { |
| 200 | self.data |
| 201 | } |
| 202 | |
| 203 | |
| 204 | pub fn into_vec(self) -> Vec<u8> { |
| 205 | self.data |
| 206 | } |
| 207 | } |
| 208 | |
| 209 | impl std::ops::Deref for $name { |
| 210 | type Target = [u8]; |
| 211 | fn deref(&self) -> &[u8] { |
| 212 | &self.data |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | impl std::ops::DerefMut for $name { |
| 217 | fn deref_mut(&mut self) -> &mut [u8] { |
| 218 | &mut self.data |
| 219 | } |
| 220 | } |
| 221 | }; |
| 222 | } |
| 223 | |
| 224 | buffer!(GrayImage, Luma, 1, "An 8-bit greyscale image buffer."); |
| 225 | buffer!(RgbImage, Rgb, 3, "An 8-bit RGB image buffer."); |
| 226 | buffer!(RgbaImage, Rgba, 4, "An 8-bit RGBA image buffer."); |
| 227 | |
| 228 | |
| 229 | #[derive(Debug, Clone, PartialEq)] |
| 230 | pub enum DynamicImage { |
| 231 | |
| 232 | ImageLuma8(GrayImage), |
| 233 | |
| 234 | ImageRgb8(RgbImage), |
| 235 | |
| 236 | ImageRgba8(RgbaImage), |
| 237 | } |
| 238 | |
| 239 | impl DynamicImage { |
| 240 | fn from_decoded(image: ec_image::Image) -> DynamicImage { |
| 241 | let (w, h) = (image.width, image.height); |
| 242 | match &image.pixels { |
| 243 | ec_image::Pixels::L8(data) => DynamicImage::ImageLuma8( |
| 244 | GrayImage::from_raw(w, h, data.clone()).expect("plane sized by the decoder"), |
| 245 | ), |
| 246 | ec_image::Pixels::Rgb8(data) => DynamicImage::ImageRgb8( |
| 247 | RgbImage::from_raw(w, h, data.clone()).expect("plane sized by the decoder"), |
| 248 | ), |
| 249 | _ if image.pixels.has_alpha() => DynamicImage::ImageRgba8( |
| 250 | RgbaImage::from_raw(w, h, image.to_rgba8()).expect("plane sized by the decoder"), |
| 251 | ), |
| 252 | _ => DynamicImage::ImageRgb8( |
| 253 | RgbImage::from_raw(w, h, image.to_rgb8()).expect("plane sized by the decoder"), |
| 254 | ), |
| 255 | } |
| 256 | } |
| 257 | |
| 258 | |
| 259 | pub fn dimensions(&self) -> (u32, u32) { |
| 260 | match self { |
| 261 | DynamicImage::ImageLuma8(b) => b.dimensions(), |
| 262 | DynamicImage::ImageRgb8(b) => b.dimensions(), |
| 263 | DynamicImage::ImageRgba8(b) => b.dimensions(), |
| 264 | } |
| 265 | } |
| 266 | |
| 267 | |
| 268 | pub fn width(&self) -> u32 { |
| 269 | self.dimensions().0 |
| 270 | } |
| 271 | |
| 272 | |
| 273 | pub fn height(&self) -> u32 { |
| 274 | self.dimensions().1 |
| 275 | } |
| 276 | |
| 277 | |
| 278 | pub fn to_rgb8(&self) -> RgbImage { |
| 279 | let (w, h) = self.dimensions(); |
| 280 | let data = match self { |
| 281 | DynamicImage::ImageRgb8(b) => return b.clone(), |
| 282 | DynamicImage::ImageLuma8(b) => b.data.iter().flat_map(|&l| [l, l, l]).collect(), |
| 283 | DynamicImage::ImageRgba8(b) => b |
| 284 | .data |
| 285 | .chunks_exact(4) |
| 286 | .flat_map(|p| p[..3].to_vec()) |
| 287 | .collect(), |
| 288 | }; |
| 289 | RgbImage::from_raw(w, h, data).expect("converted plane") |
| 290 | } |
| 291 | |
| 292 | |
| 293 | pub fn to_rgba8(&self) -> RgbaImage { |
| 294 | let (w, h) = self.dimensions(); |
| 295 | let data = match self { |
| 296 | DynamicImage::ImageRgba8(b) => return b.clone(), |
| 297 | DynamicImage::ImageLuma8(b) => b.data.iter().flat_map(|&l| [l, l, l, 255]).collect(), |
| 298 | DynamicImage::ImageRgb8(b) => b |
| 299 | .data |
| 300 | .chunks_exact(3) |
| 301 | .flat_map(|p| [p[0], p[1], p[2], 255]) |
| 302 | .collect(), |
| 303 | }; |
| 304 | RgbaImage::from_raw(w, h, data).expect("converted plane") |
| 305 | } |
| 306 | |
| 307 | |
| 308 | pub fn to_luma8(&self) -> GrayImage { |
| 309 | let (w, h) = self.dimensions(); |
| 310 | let data = match self { |
| 311 | DynamicImage::ImageLuma8(b) => return b.clone(), |
| 312 | _ => self |
| 313 | .to_rgb8() |
| 314 | .data |
| 315 | .chunks_exact(3) |
| 316 | .map(|p| { |
| 317 | let luma = |
| 318 | 2126 * u32::from(p[0]) + 7152 * u32::from(p[1]) + 722 * u32::from(p[2]); |
| 319 | ((luma + 5000) / 10000).min(255) as u8 |
| 320 | }) |
| 321 | .collect(), |
| 322 | }; |
| 323 | GrayImage::from_raw(w, h, data).expect("converted plane") |
| 324 | } |
| 325 | } |
| 326 | |
| 327 | |
| 328 | |
| 329 | |
| 330 | |
| 331 | |
| 332 | #[derive(Debug)] |
| 333 | pub struct ImageReader { |
| 334 | data: Vec<u8>, |
| 335 | format: Option<ImageFormat>, |
| 336 | } |
| 337 | |
| 338 | impl ImageReader { |
| 339 | |
| 340 | pub fn open(path: impl AsRef<Path>) -> std::io::Result<ImageReader> { |
| 341 | Ok(ImageReader { |
| 342 | data: std::fs::read(path)?, |
| 343 | format: None, |
| 344 | }) |
| 345 | } |
| 346 | |
| 347 | |
| 348 | pub fn new(data: Vec<u8>) -> ImageReader { |
| 349 | ImageReader { data, format: None } |
| 350 | } |
| 351 | |
| 352 | |
| 353 | |
| 354 | |
| 355 | |
| 356 | |
| 357 | pub fn with_guessed_format(mut self) -> std::io::Result<ImageReader> { |
| 358 | self.format = format_of(&self.data); |
| 359 | Ok(self) |
| 360 | } |
| 361 | |
| 362 | |
| 363 | pub fn format(&self) -> Option<ImageFormat> { |
| 364 | self.format |
| 365 | } |
| 366 | |
| 367 | |
| 368 | pub fn decode(self) -> ImageResult<DynamicImage> { |
| 369 | Ok(DynamicImage::from_decoded(ec_image::decode(&self.data)?)) |
| 370 | } |
| 371 | |
| 372 | |
| 373 | pub fn into_dimensions(self) -> ImageResult<(u32, u32)> { |
| 374 | let info = ec_image::info(&self.data)?; |
| 375 | Ok((info.width, info.height)) |
| 376 | } |
| 377 | } |
| 378 | |
| 379 | |
| 380 | fn format_of(data: &[u8]) -> Option<ImageFormat> { |
| 381 | match ec_image::ImageFormat::guess(data)? { |
| 382 | ec_image::ImageFormat::Png => Some(ImageFormat::Png), |
| 383 | ec_image::ImageFormat::Jpeg => Some(ImageFormat::Jpeg), |
| 384 | ec_image::ImageFormat::WebP => Some(ImageFormat::WebP), |
| 385 | |
| 386 | |
| 387 | #[cfg(feature = "gpui")] |
| 388 | ec_image::ImageFormat::Gif => Some(ImageFormat::Gif), |
| 389 | #[cfg(not(feature = "gpui"))] |
| 390 | ec_image::ImageFormat::Gif => None, |
| 391 | #[cfg(feature = "gpui")] |
| 392 | ec_image::ImageFormat::Bmp => Some(ImageFormat::Bmp), |
| 393 | #[cfg(not(feature = "gpui"))] |
| 394 | ec_image::ImageFormat::Bmp => None, |
| 395 | } |
| 396 | } |
| 397 | |
| 398 | |
| 399 | pub fn open(path: impl AsRef<Path>) -> ImageResult<DynamicImage> { |
| 400 | let data = std::fs::read(path)?; |
| 401 | load_from_memory(&data) |
| 402 | } |
| 403 | |
| 404 | |
| 405 | pub fn load_from_memory(data: &[u8]) -> ImageResult<DynamicImage> { |
| 406 | Ok(DynamicImage::from_decoded(ec_image::decode(data)?)) |
| 407 | } |
| 408 | |
| 409 | #[cfg(test)] |
| 410 | mod tests { |
| 411 | use super::*; |
| 412 | use std::path::PathBuf; |
| 413 | |
| 414 | fn fixtures() -> PathBuf { |
| 415 | Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/stills") |
| 416 | } |
| 417 | |
| 418 | |
| 419 | #[test] |
| 420 | fn the_engine_call_sequence_works() { |
| 421 | let path = fixtures().join("rgb8.png"); |
| 422 | if !path.exists() { |
| 423 | eprintln!("skipped: fixtures/stills not generated"); |
| 424 | return; |
| 425 | } |
| 426 | let reader = ImageReader::open(&path).expect("open"); |
| 427 | let rgb = reader |
| 428 | .with_guessed_format() |
| 429 | .expect("guess") |
| 430 | .decode() |
| 431 | .map_err(|e| format!("{}: {e}", path.display())) |
| 432 | .expect("decode") |
| 433 | .to_rgb8(); |
| 434 | let (width, height) = rgb.dimensions(); |
| 435 | assert_eq!((width, height), (320, 240)); |
| 436 | assert_eq!(rgb.len(), 320 * 240 * 3, "Deref reaches the samples"); |
| 437 | |
| 438 | let dimensions = ImageReader::open(&path) |
| 439 | .unwrap() |
| 440 | .with_guessed_format() |
| 441 | .unwrap() |
| 442 | .into_dimensions() |
| 443 | .expect("dimensions"); |
| 444 | assert_eq!(dimensions, (320, 240)); |
| 445 | |
| 446 | let pixel = open(&path).expect("open").to_rgb8().get_pixel(7, 9).0; |
| 447 | assert_eq!(pixel.len(), 3); |
| 448 | } |
| 449 | |
| 450 | #[test] |
| 451 | fn a_missing_file_is_an_io_error_the_caller_can_propagate() { |
| 452 | let err = ImageReader::open(fixtures().join("nope.png")).unwrap_err(); |
| 453 | assert_eq!(err.kind(), std::io::ErrorKind::NotFound); |
| 454 | let err: ImageError = err.into(); |
| 455 | assert!(matches!(err, ImageError::IoError(_)), "{err}"); |
| 456 | } |
| 457 | |
| 458 | #[test] |
| 459 | fn a_file_that_is_not_an_image_fails_at_decode_not_at_guess() { |
| 460 | let reader = ImageReader::new(b"not a picture at all".to_vec()) |
| 461 | .with_guessed_format() |
| 462 | .expect("guessing never fails on unknown bytes"); |
| 463 | assert_eq!(reader.format(), None); |
| 464 | assert!(matches!(reader.decode(), Err(ImageError::Unsupported(_)))); |
| 465 | } |
| 466 | |
| 467 | #[test] |
| 468 | fn alpha_survives_and_grey_stays_grey() { |
| 469 | let dir = fixtures(); |
| 470 | if !dir.join("rgba8.png").exists() { |
| 471 | eprintln!("skipped: fixtures/stills not generated"); |
| 472 | return; |
| 473 | } |
| 474 | let rgba = open(dir.join("rgba8.png")).unwrap(); |
| 475 | assert!(matches!(rgba, DynamicImage::ImageRgba8(_))); |
| 476 | let grey = open(dir.join("gray8.png")).unwrap(); |
| 477 | assert!(matches!(grey, DynamicImage::ImageLuma8(_))); |
| 478 | |
| 479 | let rgb = grey.to_rgb8(); |
| 480 | let p = rgb.get_pixel(3, 3).0; |
| 481 | assert_eq!(p[0], p[1]); |
| 482 | assert_eq!(p[1], p[2]); |
| 483 | } |
| 484 | } |