logo
  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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
use core::marker::PhantomData;

use embedded_graphics_core::{pixelcolor::BinaryColor, primitives::Rectangle};

use crate::{
    draw_target::DrawTarget,
    geometry::{Dimensions, OriginDimensions, Point, Size},
    image::ImageDrawable,
    iterator::raw::RawDataSlice,
    pixelcolor::{
        raw::{BigEndian, ByteOrder, LittleEndian, RawData},
        PixelColor,
    },
};

/// Image with little endian data.
pub type ImageRawLE<'a, C> = ImageRaw<'a, C, LittleEndian>;

/// Image with big endian data.
pub type ImageRawBE<'a, C> = ImageRaw<'a, C, BigEndian>;

/// An image constructed from a slice of raw pixel data.
///
/// The `ImageRaw` struct can be used to construct an image from a slice
/// of raw image data. The storage format is determined by the [`PixelColor`]
/// type `C` and the [`ByteOrder`] `BO`. The byteorder doesn't need to be
/// specified for colors which aren't stored in multiple bytes.
///
/// For color types with less than 8 bits per pixels the start of each row is
/// aligned to the next whole byte.
///
/// Details about the conversion of raw data to color types are explained in the
/// [`raw` module documentation].
///
/// To draw an `ImageRaw` object it needs to be wrapped in an [`Image`] object.
///
/// # Examples
///
/// ## Draw a 1BPP image
///
/// This example creates an image from 1 bit per pixel data.
///
/// ```
/// use embedded_graphics::{
///     image::{Image, ImageRaw},
///     pixelcolor::BinaryColor,
///     prelude::*,
/// };
/// # use embedded_graphics::mock_display::MockDisplay as Display;
///
/// /// 12 x 5 pixel image with 1 bit per pixel.
/// /// The data for each row is 12 bits long and is padded with zeros on the
/// /// end because each row needs to contain a whole number of bytes.
/// #[rustfmt::skip]
/// const DATA: &[u8] = &[
///     0b11101111, 0b0101_0000,
///     0b10001000, 0b0101_0000,
///     0b11101011, 0b0101_0000,
///     0b10001001, 0b0101_0000,
///     0b11101111, 0b0101_0000,
/// ];
///
/// // The image dimensions and the format of the stored raw data must be specified
/// // when the `new` function is called. The data format can, for example, be specified
/// // by using the turbofish syntax. For the image dimensions only the width must be
/// // passed to the `new` function. The image height will be calculated based on the
/// // length of the image data and the data format.
/// let raw_image = ImageRaw::<BinaryColor>::new(DATA, 12);
///
/// let image = Image::new(&raw_image, Point::zero());
///
/// let mut display = Display::default();
///
/// image.draw(&mut display)?;
/// # Ok::<(), core::convert::Infallible>(())
/// ```
///
/// ## Draw an image that uses multibyte pixel encoding
///
/// Colors with more than one byte per pixel need an additional type annotation for the byte order.
/// For convenience, the [`ImageRawBE`] and [`ImageRawLE`] type aliases can be used to abbreviate
/// the type.
///
/// ```
/// use embedded_graphics::{
///     image::{Image, ImageRaw, ImageRawBE, ImageRawLE},
///     pixelcolor::{
///         raw::{BigEndian, LittleEndian},
///         Rgb565, Rgb888,
///     },
///     prelude::*,
/// };
/// # const DATA: &[u8] = &[0x55; 8 * 8 * 3];
///
/// // Rgb888 image with 24 bits per pixel and big endian byte order
/// let image1 = ImageRawBE::<Rgb888>::new(DATA, 8);
/// // or:
/// let image2 = ImageRaw::<Rgb888, BigEndian>::new(DATA, 8);
/// # assert_eq!(image1, image2);
///
/// // Rgb565 image with 16 bits per pixel and little endian byte order
/// let image1 = ImageRawLE::<Rgb565>::new(DATA, 16);
/// // or:
/// let image2 = ImageRaw::<Rgb565, LittleEndian>::new(DATA, 16);
/// # assert_eq!(image1, image2);
/// ```
///
/// [`raw` module documentation]: ../pixelcolor/raw/index.html
/// [`Drawable`]: ../drawable/trait.Drawable.html
/// [`ImageRawBE`]: type.ImageRawBE.html
/// [`ImageRawLE`]: type.ImageRawLE.html
/// [`Image`]: struct.Image.html
/// [`PixelColor`]: ../pixelcolor/trait.PixelColor.html
/// [`ByteOrder`]: ../pixelcolor/raw/trait.ByteOrder.html
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub struct ImageRaw<'a, C, BO = BigEndian>
where
    C: PixelColor + From<<C as PixelColor>::Raw>,
    BO: ByteOrder,
{
    /// Image data, packed as dictated by raw data type `C::Raw`
    data: &'a [u8],

    /// Image size in pixels
    size: Size,

    pixel_type: PhantomData<C>,
    byte_order: PhantomData<BO>,
}

impl<'a, C, BO> ImageRaw<'a, C, BO>
where
    C: PixelColor + From<<C as PixelColor>::Raw>,
    BO: ByteOrder,
{
    /// Creates a new image.
    ///
    /// Only the width of the image needs to be specified. The height of the image will be
    /// calculated based on the length of the given image data. If the length of the image data
    /// isn't an integer multiple of the data length for a single row the last partial row will
    /// be ignored.
    pub fn new(data: &'a [u8], width: u32) -> Self {
        // Prevent panic for `width == 0` by returning a zero sized image.
        if width == 0 {
            return Self {
                data: &[],
                size: Size::zero(),
                pixel_type: PhantomData,
                byte_order: PhantomData,
            };
        }

        let height = data.len() / bytes_per_row(width, C::Raw::BITS_PER_PIXEL);

        Self {
            data,
            size: Size::new(width, height as u32),
            pixel_type: PhantomData,
            byte_order: PhantomData,
        }
    }

    /// Returns the actual row width in pixels.
    ///
    /// For images with less than 8 bits per pixel each row is padded to contain an integer number
    /// of bytes. This method returns the width of each row including the padding pixels.
    fn data_width(&self) -> u32 {
        if C::Raw::BITS_PER_PIXEL < 8 {
            let pixels_per_byte = 8 / C::Raw::BITS_PER_PIXEL as u32;

            bytes_per_row(self.size.width, C::Raw::BITS_PER_PIXEL) as u32 * pixels_per_byte
        } else {
            self.size.width
        }
    }
}

impl<'a> ImageRaw<'a, BinaryColor> {
    /// Creates a new binary image.
    ///
    /// Due to `const fn` limitations the `new` method cannot be used in `const` contexts. This
    /// method provides a workaround to create `ImageRaw`s with `BinaryColor` images.
    ///
    /// Only the width of the image needs to be specified. The height of the image will be
    /// calculated based on the length of the given image data.
    ///
    /// # Panics
    ///
    /// This function panics if `width == 0`.
    // MSRV: return a zero sized image instead of a panic for Rust >= 1.46.0
    //       (requires if in const function)
    // MSRV: remove this function when const functions with trait bounds are supported
    pub const fn new_binary(data: &'a [u8], width: u32) -> Self {
        let height = data.len() / bytes_per_row(width, 1);

        Self {
            data,
            size: Size::new(width, height as u32),
            pixel_type: PhantomData,
            byte_order: PhantomData,
        }
    }
}

/// Returns the length of each row in bytes.
const fn bytes_per_row(width: u32, bits_per_pixel: usize) -> usize {
    (width as usize * bits_per_pixel + 7) / 8
}

impl<'a, C, BO> ImageDrawable for ImageRaw<'a, C, BO>
where
    C: PixelColor + From<<C as PixelColor>::Raw>,
    BO: ByteOrder,
    RawDataSlice<'a, C::Raw, BO>: IntoIterator<Item = C::Raw>,
{
    type Color = C;

    fn draw<D>(&self, target: &mut D) -> Result<(), D::Error>
    where
        D: DrawTarget<Color = C>,
    {
        let row_skip = self.data_width() - self.size.width;

        target.fill_contiguous(
            &self.bounding_box(),
            ContiguousPixels::new(self, self.size, 0, row_skip as usize),
        )
    }

    fn draw_sub_image<D>(&self, target: &mut D, area: &Rectangle) -> Result<(), D::Error>
    where
        D: DrawTarget<Color = Self::Color>,
    {
        // Don't draw anything if `area` is zero sized or partially outside the image.
        if area.is_zero_sized()
            || area.top_left.x < 0
            || area.top_left.y < 0
            || area.top_left.x as u32 + area.size.width > self.size.width
            || area.top_left.y as u32 + area.size.height > self.size.height
        {
            return Ok(());
        }

        let data_width = self.data_width() as usize;

        let initial_skip = area.top_left.y as usize * data_width + area.top_left.x as usize;
        let row_skip = data_width - area.size.width as usize;

        target.fill_contiguous(
            &Rectangle::new(Point::zero(), area.size),
            ContiguousPixels::new(self, area.size, initial_skip, row_skip),
        )
    }
}

impl<C, BO> OriginDimensions for ImageRaw<'_, C, BO>
where
    C: PixelColor + From<<C as PixelColor>::Raw>,
    BO: ByteOrder,
{
    fn size(&self) -> Size {
        self.size
    }
}

struct ContiguousPixels<'a, C, BO>
where
    C: PixelColor + From<<C as PixelColor>::Raw>,
    BO: ByteOrder,
    RawDataSlice<'a, C::Raw, BO>: IntoIterator<Item = C::Raw>,
{
    iter: <RawDataSlice<'a, C::Raw, BO> as IntoIterator>::IntoIter,

    remaining_x: u32,
    width: u32,

    remaining_y: u32,
    row_skip: usize,
}

impl<'a, C, BO> ContiguousPixels<'a, C, BO>
where
    C: PixelColor + From<<C as PixelColor>::Raw>,
    BO: ByteOrder,
    RawDataSlice<'a, C::Raw, BO>: IntoIterator<Item = C::Raw>,
{
    fn new(image: &ImageRaw<'a, C, BO>, size: Size, initial_skip: usize, row_skip: usize) -> Self {
        let mut iter = RawDataSlice::new(image.data).into_iter();

        if initial_skip > 0 {
            iter.nth(initial_skip - 1);
        }

        // Set `remaining_y` to `0` if `width == 0` to prevent integer underflow in `next`.
        let remaining_y = if size.width > 0 { size.height } else { 0 };

        Self {
            iter,
            remaining_x: size.width,
            width: size.width,
            remaining_y,
            row_skip,
        }
    }
}

impl<'a, C, BO> Iterator for ContiguousPixels<'a, C, BO>
where
    C: PixelColor + From<<C as PixelColor>::Raw>,
    BO: ByteOrder,
    RawDataSlice<'a, C::Raw, BO>: IntoIterator<Item = C::Raw>,
{
    type Item = C;

    fn next(&mut self) -> Option<Self::Item> {
        if self.remaining_x > 0 {
            self.remaining_x -= 1;

            self.iter.next()
        } else {
            if self.remaining_y == 0 {
                return None;
            }

            self.remaining_y -= 1;
            self.remaining_x = self.width - 1;

            self.iter.nth(self.row_skip)
        }
        .map(|c| c.into())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        draw_target::DrawTarget,
        geometry::Point,
        image::Image,
        iterator::PixelIteratorExt,
        mock_display::{ColorMapping, MockDisplay},
        pixelcolor::{raw::RawU32, *},
        Drawable, Pixel,
    };

    #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Default)]
    struct TestColorU32(RawU32);

    impl PixelColor for TestColorU32 {
        type Raw = RawU32;
    }

    impl From<RawU32> for TestColorU32 {
        fn from(data: RawU32) -> Self {
            Self(data)
        }
    }

    /// Tests if the given image data matches an excepted `MockDisplay` pattern.
    fn assert_pattern<C, BO>(image_data: ImageRaw<C, BO>, expected_pattern: &[&str])
    where
        C: PixelColor + From<<C as PixelColor>::Raw> + ColorMapping,
        BO: ByteOrder,
        for<'a> RawDataSlice<'a, C::Raw, BO>: IntoIterator<Item = C::Raw>,
    {
        let image = Image::new(&image_data, Point::zero());
        let mut display = MockDisplay::new();
        image.draw(&mut display).unwrap();

        display.assert_pattern(expected_pattern);
    }

    #[test]
    fn image_dimensions() {
        let data = [
            0xAA, 0x00, //
            0x55, 0xFF, //
            0xAA, 0x80, //
        ];
        let image_data: ImageRaw<BinaryColor> = ImageRaw::new(&data, 9);

        assert_eq!(image_data.size(), Size::new(9, 3));
    }

    #[test]
    fn truncated_data() {
        let data = [
            0xAA, 0x00, //
            0x55, 0xFF, //
            0xAA, //
        ];
        let image_data: ImageRaw<BinaryColor> = ImageRaw::new(&data, 9);

        assert_pattern(
            image_data,
            &[
                "#.#.#.#..", //
                ".#.#.#.##", //
            ],
        );
    }

    #[test]
    fn bpp1_new() {
        let data = [
            0xAA, 0x00, //
            0x55, 0xFF, //
            0xAA, 0x80, //
        ];
        let image_data: ImageRaw<BinaryColor> = ImageRaw::new(&data, 9);

        assert_pattern(
            image_data,
            &[
                "#.#.#.#..", //
                ".#.#.#.##", //
                "#.#.#.#.#", //
            ],
        );
    }

    #[test]
    fn bpp1_new_binary() {
        let data = [
            0xAA, 0x00, //
            0x55, 0xFF, //
            0xAA, 0x80, //
        ];
        let image_data = ImageRaw::new_binary(&data, 9);

        assert_pattern(
            image_data,
            &[
                "#.#.#.#..", //
                ".#.#.#.##", //
                "#.#.#.#.#", //
            ],
        );
    }

    #[test]
    fn bpp2() {
        let data = [
            0b00_01_10_11, //
            0b00_00_00_00, //
            0b11_10_01_00, //
            0b11_11_11_11, //
        ];
        let image_data: ImageRaw<Gray2> = ImageRaw::new(&data, 5);

        assert_pattern(
            image_data,
            &[
                "01230", //
                "32103", //
            ],
        );
    }

    #[test]
    fn bpp4() {
        let data = [
            0b0001_1000, //
            0b1111_0000, //
            0b0101_1010, //
            0b0000_0000, //
        ];
        let image_data: ImageRaw<Gray4> = ImageRaw::new(&data, 3);

        assert_pattern(
            image_data,
            &[
                "18F", //
                "5A0", //
            ],
        );
    }

    #[test]
    fn bpp8_1() {
        let data = [
            0x11, 0x22, //
            0x33, 0x44, //
            0x55, 0x66, //
        ];
        let image_data: ImageRaw<Gray8> = ImageRaw::new(&data, 2);

        assert_pattern(
            image_data,
            &[
                "12", //
                "34", //
                "56", //
            ],
        );
    }

    /// Additional test for luma values with different low and high nibbles,
    /// which are not supported by `MockDisplay` patterns.
    #[test]
    fn bpp8_2() {
        let data = [0x01, 0x08, 0x10, 0x80];
        let image_data: ImageRaw<Gray8> = ImageRaw::new(&data, 4);

        let mut display = MockDisplay::new();
        Image::new(&image_data, Point::zero())
            .draw(&mut display)
            .unwrap();

        let mut expected = MockDisplay::new();
        expected
            .fill_contiguous(
                &expected.bounding_box(),
                data.iter().copied().map(Gray8::new),
            )
            .unwrap();

        display.assert_eq(&expected);
    }

    #[test]
    fn bpp16_little_endian() {
        let data = [
            0x00, 0xF8, //
            0xE0, 0x07, //
            0x1F, 0x00, //
            0x00, 0x00, //
        ];
        let image_data: ImageRawLE<Rgb565> = ImageRaw::new(&data, 1);

        assert_pattern(
            image_data,
            &[
                "R", //
                "G", //
                "B", //
                "K", //
            ],
        );
    }

    #[test]
    fn bpp16_big_endian() {
        let data = [
            0xF8, 0x00, //
            0x07, 0xE0, //
            0x00, 0x1F, //
            0x00, 0x00, //
        ];
        let image_data: ImageRawBE<Rgb565> = ImageRaw::new(&data, 2);

        assert_pattern(
            image_data,
            &[
                "RG", //
                "BK", //
            ],
        );
    }

    #[test]
    fn bpp24_little_endian() {
        let data = [
            0xFF, 0x00, 0x00, //
            0x00, 0xFF, 0x00, //
            0x00, 0x00, 0xFF, //
            0x00, 0x00, 0x00, //
        ];
        let image_data: ImageRawLE<Bgr888> = ImageRaw::new(&data, 1);

        assert_pattern(
            image_data,
            &[
                "R", //
                "G", //
                "B", //
                "K", //
            ],
        );
    }

    #[test]
    fn bpp24_big_endian() {
        let data = [
            0xFF, 0x00, 0x00, //
            0x00, 0xFF, 0x00, //
            0x00, 0x00, 0xFF, //
            0x00, 0x00, 0x00, //
        ];
        let image_data: ImageRawBE<Rgb888> = ImageRaw::new(&data, 4);

        assert_pattern(image_data, &["RGBK"]);
    }

    #[test]
    fn bpp32_little_endian() {
        let data = [
            0x12, 0x34, 0x56, 0x78, //
            0x9A, 0xBC, 0xDE, 0xF0, //
            0x00, 0x00, 0x00, 0x00, //
            0xFF, 0xFF, 0xFF, 0xFF, //
        ];
        let image_data: ImageRawLE<TestColorU32> = ImageRaw::new(&data, 2);

        let mut display = MockDisplay::new();
        Image::new(&image_data, Point::zero())
            .draw(&mut display)
            .unwrap();

        let expected = [
            Pixel(Point::new(0, 0), TestColorU32(RawU32::new(0x78563412))),
            Pixel(Point::new(1, 0), TestColorU32(RawU32::new(0xF0DEBC9A))),
            Pixel(Point::new(0, 1), TestColorU32(RawU32::new(0x00000000))),
            Pixel(Point::new(1, 1), TestColorU32(RawU32::new(0xFFFFFFFF))),
        ];

        let mut expected_display = MockDisplay::new();
        expected
            .iter()
            .copied()
            .draw(&mut expected_display)
            .unwrap();

        // assert_eq can't be used here because ColorMapping isn't implemented for TestColorU32
        assert!(display.eq(&expected_display));
    }

    #[test]
    fn bpp32_big_endian() {
        let data = [
            0x12, 0x34, 0x56, 0x78, //
            0x9A, 0xBC, 0xDE, 0xF0, //
            0x00, 0x00, 0x00, 0x00, //
            0xFF, 0xFF, 0xFF, 0xFF, //
        ];
        let image_data: ImageRawBE<TestColorU32> = ImageRaw::new(&data, 4);

        let mut display = MockDisplay::new();
        Image::new(&image_data, Point::zero())
            .draw(&mut display)
            .unwrap();

        let expected = [
            Pixel(Point::new(0, 0), TestColorU32(RawU32::new(0x12345678))),
            Pixel(Point::new(1, 0), TestColorU32(RawU32::new(0x9ABCDEF0))),
            Pixel(Point::new(2, 0), TestColorU32(RawU32::new(0x00000000))),
            Pixel(Point::new(3, 0), TestColorU32(RawU32::new(0xFFFFFFFF))),
        ];

        let mut expected_display = MockDisplay::new();
        expected
            .iter()
            .copied()
            .draw(&mut expected_display)
            .unwrap();

        // assert_eq can't be used here because ColorMapping isn't implemented for TestColorU32
        assert!(display.eq(&expected_display));
    }

    #[test]
    fn calculated_height() {
        let data = [0u8; 1];
        assert_eq!(ImageRaw::<BinaryColor>::new(&data, 12).size().height, 0);

        let data = [0u8; 2];
        assert_eq!(ImageRaw::<BinaryColor>::new(&data, 12).size().height, 1);

        let data = [0u8; 3];
        assert_eq!(ImageRaw::<BinaryColor>::new(&data, 12).size().height, 1);

        let data = [0u8; 4];
        assert_eq!(ImageRaw::<BinaryColor>::new(&data, 12).size().height, 2);
    }
}