| 1 | use std::io::Cursor; |
| 2 | |
| 3 | use gpui_kit::ImageFormat; |
| 4 | |
| 5 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 6 | pub enum InlineFormat { |
| 7 | Png, |
| 8 | Jpeg, |
| 9 | Gif, |
| 10 | Webp, |
| 11 | } |
| 12 | |
| 13 | impl InlineFormat { |
| 14 | pub fn image_format(self) -> ImageFormat { |
| 15 | match self { |
| 16 | InlineFormat::Png => ImageFormat::Png, |
| 17 | InlineFormat::Jpeg => ImageFormat::Jpeg, |
| 18 | InlineFormat::Gif => ImageFormat::Gif, |
| 19 | InlineFormat::Webp => ImageFormat::Webp, |
| 20 | } |
| 21 | } |
| 22 | |
| 23 | pub fn decoder_format(self) -> Option<image::ImageFormat> { |
| 24 | match self { |
| 25 | InlineFormat::Png => Some(image::ImageFormat::Png), |
| 26 | InlineFormat::Jpeg => Some(image::ImageFormat::Jpeg), |
| 27 | InlineFormat::Webp => Some(image::ImageFormat::WebP), |
| 28 | InlineFormat::Gif => None, |
| 29 | } |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | pub fn sniff_inline_format(bytes: &[u8]) -> Option<InlineFormat> { |
| 34 | match bytes { |
| 35 | [0x89, b'P', b'N', b'G', ..] => Some(InlineFormat::Png), |
| 36 | [0xFF, 0xD8, 0xFF, ..] => Some(InlineFormat::Jpeg), |
| 37 | [b'G', b'I', b'F', b'8', ..] => Some(InlineFormat::Gif), |
| 38 | [ |
| 39 | b'R', |
| 40 | b'I', |
| 41 | b'F', |
| 42 | b'F', |
| 43 | _, |
| 44 | _, |
| 45 | _, |
| 46 | _, |
| 47 | b'W', |
| 48 | b'E', |
| 49 | b'B', |
| 50 | b'P', |
| 51 | .., |
| 52 | ] => Some(InlineFormat::Webp), |
| 53 | _ => None, |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | pub fn image_dimensions(format: InlineFormat, bytes: &[u8]) -> Option<(u32, u32)> { |
| 58 | match format.decoder_format() { |
| 59 | Some(decoder) => image::ImageReader::with_format(Cursor::new(bytes), decoder) |
| 60 | .into_dimensions() |
| 61 | .ok(), |
| 62 | None => { |
| 63 | let header = bytes.get(6..10)?; |
| 64 | Some(( |
| 65 | u32::from(u16::from_le_bytes([header[0], header[1]])), |
| 66 | u32::from(u16::from_le_bytes([header[2], header[3]])), |
| 67 | )) |
| 68 | } |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | pub fn dimensions_of(bytes: &[u8]) -> Option<(u32, u32)> { |
| 73 | image_dimensions(sniff_inline_format(bytes)?, bytes) |
| 74 | } |