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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
//! Image support for embedded-graphics
//!
//! Adding embedded-graphics support to an image format requires the implementation of the
//! [`ImageDimensions`] and [`IntoPixelIter`] traits. These provide a common interface to image metadata
//! and an iterator over individual pixel values respectively.
//!
//! The [`Image`] struct is a wrapper around items that implement both [`ImageDimensions`] and
//! [`IntoPixelIter`] and allows them to be drawn to a [`DrawTarget`], reading pixel values from the
//! implementation of [`IntoPixelIter`].
//!
//! # Examples
//!
//! ## Load a TGA image and draw it to a display
//!
//! This example loads a TGA-formatted image using the [tinytga] crate and draws it to the display
//! using the [`Image`] wrapper. The image is positioned at the top left corner of the display.
//!
//! ```rust
//! use embedded_graphics::{image::Image, pixelcolor::Rgb565, prelude::*};
//! # use embedded_graphics::mock_display::MockDisplay as Display;
//! use tinytga::Tga;
//!
//! let mut display: Display<Rgb565> = Display::default();
//!
//! let tga =
//!     Tga::from_slice(include_bytes!("../../../simulator/examples/assets/rust-pride.tga")).unwrap();
//!
//! let image: Image<Tga, Rgb565> = Image::new(&tga, Point::zero());
//!
//! image.draw(&mut display);
//!
//! # Ok::<(), core::convert::Infallible>(())
//! ```
//!
//! [tinytga]: https://crates.io/crates/tinytga
//! [`IntoPixelIter`]: ./trait.IntoPixelIter.html
//! [`ImageDimensions`]: ./trait.ImageDimensions.html
//! [`Image`]: ./struct.Image.html
//! [`DrawTarget`]: ../trait.DrawTarget.html

mod image_raw;

pub use self::image_raw::{ImageRaw, ImageRawBE, ImageRawLE};

use crate::{
    draw_target::DrawTarget,
    drawable::{Drawable, Pixel},
    geometry::{Dimensions, Point, Size},
    pixelcolor::PixelColor,
    transform::Transform,
};
use core::fmt::Debug;
use core::{fmt, marker::PhantomData};

/// Conversion into an iterator over the pixels of the image.
pub trait IntoPixelIter<C>
where
    C: PixelColor + From<<C as PixelColor>::Raw>,
{
    /// Iterator over pixels in the image
    type PixelIterator: Iterator<Item = Pixel<C>>;

    /// Get an iterator over the pixels of the image
    fn pixel_iter(self) -> Self::PixelIterator;
}

/// A trait to get the dimensions of an image.
///
/// This trait provides an interface to get the width and height of an image. It should be
/// implemented along with [`IntoPixelIter`] for full embedded-graphics integration.
pub trait ImageDimensions {
    /// Get the width in pixels of an image
    fn width(&self) -> u32;

    /// Get the height in pixels of an image
    fn height(&self) -> u32;
}

/// Image drawable.
///
/// The `Image` struct serves as a wrapper around other image types that provide pixel data decoded
/// from a given format (raw bytes, BMP, TGA, etc). It allows an image to be repositioned using
/// [`Transform::translate()`] or [`Transform::translate_mut()`] and drawn to a display that
/// implements the [`DrawTarget`] trait.
///
/// `Image` accepts any item that implements `ImageDimensions` and `&'_ IntoPixelIter`.
///
/// Refer to the [module documentation] for examples.
///
/// [module documentation]: ./index.html
/// [`Transform::translate()`]: ../transform/trait.Transform.html#tymethod.translate
/// [`Transform::translate_mut()`]: ../transform/trait.Transform.html#tymethod.translate_mut
/// [`DrawTarget`]: ../trait.DrawTarget.html
#[derive(Debug, Clone, Copy)]
pub struct Image<'a, I, C> {
    image_data: &'a I,
    offset: Point,
    c: PhantomData<C>,
}

impl<'a, I, C> Image<'a, I, C>
where
    &'a I: IntoPixelIter<C>,
    I: ImageDimensions,
    C: PixelColor + From<<C as PixelColor>::Raw>,
{
    /// Create a new `Image` with the given image pixel data.
    ///
    /// The passed [`IntoPixelIter`] provides a source of pixel data from the original image.
    ///
    /// [`IntoPixelIter`]: ./trait.IntoPixelIter.html
    pub fn new(image_data: &'a I, position: Point) -> Self {
        Self {
            image_data,
            offset: position,
            c: PhantomData,
        }
    }
}

impl<I, C> Transform for Image<'_, I, C> {
    /// Translate the image by a given delta, returning a new image
    ///
    /// # Examples
    ///
    /// ## Move an image around
    ///
    /// This examples moves a 4x4 black and white image by `(10, 20)` pixels without mutating the
    /// original image
    ///
    /// ```rust
    /// use embedded_graphics::{
    ///     geometry::Point,
    ///     image::{Image, ImageRaw},
    ///     pixelcolor::BinaryColor,
    ///     prelude::*,
    /// };
    ///
    /// let image: ImageRaw<BinaryColor> = ImageRaw::new(&[0xff, 0x00, 0xff, 0x00], 4, 4);
    ///
    /// let image: Image<_, BinaryColor> = Image::new(&image, Point::zero());
    ///
    /// let image_moved = image.translate(Point::new(10, 20));
    ///
    /// assert_eq!(image.top_left(), Point::zero());
    /// assert_eq!(image_moved.top_left(), Point::new(10, 20));
    /// ```
    fn translate(&self, by: Point) -> Self {
        Self {
            image_data: self.image_data,
            offset: self.offset + by,
            c: PhantomData,
        }
    }

    /// Translate the image by a given delta, modifying the original object
    ///
    /// # Examples
    ///
    /// ## Move an image around
    ///
    /// This examples moves a 4x4 black and white image by `(10, 20)` pixels by mutating the
    /// original image
    ///
    /// ```rust
    /// use embedded_graphics::{
    ///     geometry::Point,
    ///     image::{Image, ImageRaw},
    ///     pixelcolor::BinaryColor,
    ///     prelude::*,
    /// };
    ///
    /// let image: ImageRaw<BinaryColor> = ImageRaw::new(&[0xff, 0x00, 0xff, 0x00], 4, 4);
    ///
    /// let mut image: Image<_, BinaryColor> = Image::new(&image, Point::zero());
    ///
    /// image.translate_mut(Point::new(10, 20));
    ///
    /// assert_eq!(image.top_left(), Point::new(10, 20));
    /// ```
    fn translate_mut(&mut self, by: Point) -> &mut Self {
        self.offset += by;

        self
    }
}

impl<'a, 'b, I, C> Drawable<C> for &'a Image<'b, I, C>
where
    &'b I: IntoPixelIter<C>,
    I: ImageDimensions,
    C: PixelColor + From<<C as PixelColor>::Raw>,
{
    fn draw<D: DrawTarget<C>>(self, display: &mut D) -> Result<(), D::Error> {
        display.draw_image(self)
    }
}

impl<'a, I, C> Dimensions for Image<'a, I, C>
where
    I: ImageDimensions,
    C: PixelColor + From<<C as PixelColor>::Raw>,
{
    fn top_left(&self) -> Point {
        self.offset
    }

    fn bottom_right(&self) -> Point {
        self.top_left() + self.size()
    }

    fn size(&self) -> Size {
        Size::new(self.image_data.width(), self.image_data.height())
    }
}

impl<'a, 'b, I, C> IntoIterator for &'a Image<'b, I, C>
where
    &'b I: IntoPixelIter<C>,
    C: PixelColor + From<<C as PixelColor>::Raw>,
{
    type Item = Pixel<C>;
    type IntoIter = ImageIterator<'a, 'b, I, C>;

    fn into_iter(self) -> Self::IntoIter {
        ImageIterator {
            it: self.image_data.pixel_iter(),
            image: self,
        }
    }
}

/// Pixel iterator over `Image` objects
pub struct ImageIterator<'a, 'b, I, C>
where
    &'b I: IntoPixelIter<C>,
    C: PixelColor + From<<C as PixelColor>::Raw>,
{
    image: &'a Image<'b, I, C>,
    it: <&'b I as IntoPixelIter<C>>::PixelIterator,
}

impl<'a, 'b, I, C> Debug for ImageIterator<'a, 'b, I, C>
where
    &'b I: IntoPixelIter<C> + Debug,
    <&'b I as IntoPixelIter<C>>::PixelIterator: Debug,
    I: Debug,
    C: PixelColor + From<<C as PixelColor>::Raw> + Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("ImageIterator")
            .field("image", &self.image)
            .field("it", &self.it)
            .finish()
    }
}

impl<'a, 'b, I, C> Iterator for ImageIterator<'a, 'b, I, C>
where
    &'b I: IntoPixelIter<C>,
    C: PixelColor + From<<C as PixelColor>::Raw>,
{
    type Item = Pixel<C>;

    fn next(&mut self) -> Option<Self::Item> {
        self.it.next().map(|p| Pixel(p.0 + self.image.offset, p.1))
    }
}