Skip to main content

zune_image/codecs/
bmp.rs

1/*
2 * Copyright (c) 2023.
3 *
4 * This software is free software;
5 *
6 * You can redistribute it or modify it under terms of the MIT, Apache License or Zlib license
7 */
8#![cfg_attr(feature = "docs", doc(cfg(feature = "bmp")))]
9#![cfg(feature = "bmp")]
10
11//! BMP decoding support
12//!
13//! Decoding is done by the delegate library [zune-bmp](zune_bmp)
14
15pub use zune_bmp::*;
16use zune_core::bytestream::ZByteReaderTrait;
17use zune_core::colorspace::ColorSpace;
18
19use crate::codecs::ImageFormat;
20use crate::errors::ImageErrors;
21use crate::image::Image;
22use crate::metadata::ImageMetadata;
23use crate::traits::{DecodeInto, DecoderTrait};
24
25impl<T> DecoderTrait for BmpDecoder<T>
26where
27    T: ZByteReaderTrait
28{
29    fn decode(&mut self) -> Result<Image, ImageErrors> {
30        let pixels = self.decode()?;
31        let (width, height) = self.dimensions().unwrap();
32        let colorspace = self.colorspace().unwrap();
33
34        Ok(Image::from_u8(&pixels, width, height, colorspace))
35    }
36
37    fn dimensions(&self) -> Option<(usize, usize)> {
38        self.dimensions()
39    }
40
41    fn out_colorspace(&self) -> ColorSpace {
42        self.colorspace().unwrap()
43    }
44
45    fn name(&self) -> &'static str {
46        "BMP Decoder"
47    }
48
49    fn read_headers(&mut self) -> Result<Option<ImageMetadata>, ImageErrors> {
50        self.decode_headers()?;
51
52        let (width, height) = self.dimensions().unwrap();
53        let depth = self.depth();
54
55        let metadata = ImageMetadata {
56            format: Some(ImageFormat::BMP),
57            colorspace: self.colorspace().expect("Impossible"),
58            depth: depth,
59            width: width,
60            height: height,
61            icc_chunk: self.icc_profile().cloned(),
62            ..Default::default()
63        };
64
65        Ok(Some(metadata))
66    }
67}
68
69impl From<BmpDecoderErrors> for ImageErrors {
70    fn from(value: BmpDecoderErrors) -> Self {
71        Self::ImageDecodeErrors(format!("bmp: {:?}", value))
72    }
73}
74
75impl<T> DecodeInto for BmpDecoder<T>
76where
77    T: ZByteReaderTrait
78{
79    type BufferType = u8;
80
81    fn decode_into(&mut self, buffer: &mut [Self::BufferType]) -> Result<(), ImageErrors> {
82        self.decode_into(buffer)
83            .map_err(<BmpDecoderErrors as Into<ImageErrors>>::into)?;
84
85        Ok(())
86    }
87
88    fn decode_output_buffer_size(&mut self) -> Result<usize, ImageErrors> {
89        self.decode_headers()
90            .map_err(<BmpDecoderErrors as Into<ImageErrors>>::into)?;
91
92        // unwrap is okay because we successfully decoded image headers
93        Ok(self.output_buf_size().unwrap())
94    }
95}