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
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
use std;
use std::io;

/// A decoded icon image.
///
/// An `Image` struct consists of a width, a height, a
/// [`PixelFormat`](enum.PixelFormat.html), and a data array encoding the image
/// pixels in that format.
///
/// Regardless of format, pixel data for an image is always stored one complete
/// pixel at a time, in row-major order (that is, the top-left pixel comes
/// first, followed by the rest of the top row from left to right; then comes
/// the second row down, again from left to right, and so on until finally the
/// bottom-right pixel comes last).
#[derive(Clone)]
pub struct Image {
    pub(crate) format: PixelFormat,
    pub(crate) width: u32,
    pub(crate) height: u32,
    pub(crate) data: Box<[u8]>,
}

impl Image {
    /// Creates a new image with all pixel data set to zero.
    pub fn new(format: PixelFormat, width: u32, height: u32) -> Image {
        let data_bits = format.bits_per_pixel() * width * height;
        let data_bytes = ((data_bits + 7) / 8) as usize;
        Image {
            format,
            width,
            height,
            data: vec![0u8; data_bytes].into_boxed_slice(),
        }
    }

    /// Creates a new image using the given pixel data.  Returns an error if
    /// the data array is not the correct length.
    pub fn from_data(
        format: PixelFormat,
        width: u32,
        height: u32,
        data: Vec<u8>,
    ) -> io::Result<Image> {
        let data_bits = format.bits_per_pixel() * width * height;
        let data_bytes = ((data_bits + 7) / 8) as usize;
        if data.len() == data_bytes {
            Ok(Image {
                format,
                width,
                height,
                data: data.into_boxed_slice(),
            })
        } else {
            let msg = format!(
                "incorrect pixel data array length for \
                               speicifed format and dimensions ({} instead \
                               of {})",
                data.len(),
                data_bytes
            );
            Err(io::Error::new(io::ErrorKind::InvalidInput, msg))
        }
    }

    /// Returns the format in which this image's pixel data is stored.
    pub fn pixel_format(&self) -> PixelFormat {
        self.format
    }

    /// Returns the width of the image, in pixels.
    pub fn width(&self) -> u32 {
        self.width
    }

    /// Returns the height of the image, in pixels.
    pub fn height(&self) -> u32 {
        self.height
    }

    /// Returns a reference to the image's pixel data.
    pub fn data(&self) -> &[u8] {
        &self.data
    }

    /// Returns a mutable reference to the image's pixel data.
    pub fn data_mut(&mut self) -> &mut [u8] {
        &mut self.data
    }

    /// Consumes the image, returning the pixel data without cloning it.
    pub fn into_data(self) -> Box<[u8]> {
        self.data
    }

    /// Creates a copy of this image by converting to the specified pixel
    /// format.  This operation always succeeds, but may lose information (e.g.
    /// converting from RGBA to RGB will silently drop the alpha channel).  If
    /// the source image is already in the requested format, this is equivalant
    /// to simply calling `clone()`.
    pub fn convert_to(&self, format: PixelFormat) -> Image {
        let new_data = match self.format {
            PixelFormat::RGBA => match format {
                PixelFormat::RGBA => self.data.clone(),
                PixelFormat::RGB => rgba_to_rgb(&self.data),
                PixelFormat::GrayAlpha => rgba_to_grayalpha(&self.data),
                PixelFormat::Gray => rgba_to_gray(&self.data),
                PixelFormat::Alpha => rgba_to_alpha(&self.data),
                PixelFormat::PNG => return self.make_png_image(),
            },
            PixelFormat::RGB => match format {
                PixelFormat::RGBA => rgb_to_rgba(&self.data),
                PixelFormat::RGB => self.data.clone(),
                PixelFormat::GrayAlpha => rgb_to_grayalpha(&self.data),
                PixelFormat::Gray => rgb_to_gray(&self.data),
                PixelFormat::Alpha => rgb_to_alpha(&self.data),
                PixelFormat::PNG => return self.make_png_image(),
            },
            PixelFormat::GrayAlpha => match format {
                PixelFormat::RGBA => grayalpha_to_rgba(&self.data),
                PixelFormat::RGB => grayalpha_to_rgb(&self.data),
                PixelFormat::GrayAlpha => self.data.clone(),
                PixelFormat::Gray => grayalpha_to_gray(&self.data),
                PixelFormat::Alpha => grayalpha_to_alpha(&self.data),
                PixelFormat::PNG => return self.make_png_image(),
            },
            PixelFormat::Gray => match format {
                PixelFormat::RGBA => gray_to_rgba(&self.data),
                PixelFormat::RGB => gray_to_rgb(&self.data),
                PixelFormat::GrayAlpha => gray_to_grayalpha(&self.data),
                PixelFormat::Gray => self.data.clone(),
                PixelFormat::Alpha => gray_to_alpha(&self.data),
                PixelFormat::PNG => return self.make_png_image(),
            },
            PixelFormat::Alpha => match format {
                PixelFormat::RGBA => alpha_to_rgba(&self.data),
                PixelFormat::RGB => alpha_to_rgb(&self.data),
                PixelFormat::GrayAlpha => alpha_to_grayalpha(&self.data),
                PixelFormat::Gray => alpha_to_gray(&self.data),
                PixelFormat::Alpha => self.data.clone(),
                PixelFormat::PNG => return self.make_png_image(),
            },
            PixelFormat::PNG => match format {
                PixelFormat::PNG => self.data.clone(),
                _ => {
                    return Image::decode_from_png(&*self.data)
                        .expect("Unable to read PNG")
                        .convert_to(format)
                }
            },
        };
        Image {
            format,
            width: self.width,
            height: self.height,
            data: new_data,
        }
    }

    fn make_png_image(&self) -> Image {
        let mut v = Vec::new();
        self.write_png(&mut v).expect("Unable to write to PNG");
        Image {
            format: PixelFormat::PNG,
            width: self.width,
            height: self.height,
            data: v.into_boxed_slice(),
        }
    }
}

/// Formats for storing pixel data in an image.
///
/// This type determines how the raw data array of an
/// [`Image`](struct.Image.html) is to be interpreted.
///
/// Regardless of format, pixel data for an image is always stored one complete
/// pixel at a time, in row-major order (that is, the top-left pixel comes
/// first, followed by the rest of the top row from left to right; then comes
/// the second row down, again from left to right, and so on until finally the
/// bottom-right pixel comes last).
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum PixelFormat {
    /// 32-bit color with alpha channel.  Each pixel is four bytes, with red
    /// first and alpha last.
    RGBA,
    /// 24-bit color with no alpha.  Each pixel is three bytes, with red
    /// first and blue last.
    RGB,
    /// 16-bit grayscale-with-alpha.  Each pixel is two bytes, with the
    /// grayscale value first and alpha second.
    GrayAlpha,
    /// 8-bit grayscale with no alpha.  Each pixel is one byte (0=black,
    /// 255=white).
    Gray,
    /// 8-bit alpha mask with no color.  Each pixel is one byte (0=transparent,
    /// 255=opaque).
    Alpha,
    /// PNG data.
    PNG,
}

impl PixelFormat {
    /// Returns the number of bits needed to store a single pixel in this
    /// format.
    pub fn bits_per_pixel(self) -> u32 {
        match self {
            PixelFormat::RGBA => 32,
            PixelFormat::RGB => 24,
            PixelFormat::GrayAlpha => 16,
            PixelFormat::Gray => 8,
            PixelFormat::Alpha => 8,
            PixelFormat::PNG => panic!("Unable to know definite number of bits per pixel for PNG"),
        }
    }
}

/// Converts RGBA image data into RGB.
fn rgba_to_rgb(rgba: &[u8]) -> Box<[u8]> {
    assert_eq!(rgba.len() % 4, 0);
    let num_pixels = rgba.len() / 4;
    let mut rgb = Vec::with_capacity(num_pixels * 3);
    for i in 0..num_pixels {
        rgb.extend_from_slice(&rgba[(4 * i)..(4 * i + 3)]);
    }
    rgb.into_boxed_slice()
}

/// Converts RGB image data into RGBA.
fn rgb_to_rgba(rgb: &[u8]) -> Box<[u8]> {
    assert_eq!(rgb.len() % 3, 0);
    let num_pixels = rgb.len() / 3;
    let mut rgba = Vec::with_capacity(num_pixels * 4);
    for i in 0..num_pixels {
        rgba.extend_from_slice(&rgb[(3 * i)..(3 * i + 3)]);
        rgba.push(std::u8::MAX);
    }
    rgba.into_boxed_slice()
}

/// Converts RGBA image data into grayscale.
fn rgba_to_gray(rgba: &[u8]) -> Box<[u8]> {
    assert_eq!(rgba.len() % 4, 0);
    let num_pixels = rgba.len() / 4;
    let mut gray = Vec::with_capacity(num_pixels);
    for i in 0..num_pixels {
        let red = u32::from(rgba[4 * i]);
        let green = u32::from(rgba[4 * i + 1]);
        let blue = u32::from(rgba[4 * i + 2]);
        gray.push(((red + green + blue) / 3) as u8);
    }
    gray.into_boxed_slice()
}

/// Converts RGB image data into grayscale.
fn rgb_to_gray(rgb: &[u8]) -> Box<[u8]> {
    assert_eq!(rgb.len() % 3, 0);
    let num_pixels = rgb.len() / 3;
    let mut gray = Vec::with_capacity(num_pixels);
    for i in 0..num_pixels {
        let red = u32::from(rgb[3 * i]);
        let green = u32::from(rgb[3 * i + 1]);
        let blue = u32::from(rgb[3 * i + 2]);
        gray.push(((red + green + blue) / 3) as u8);
    }
    gray.into_boxed_slice()
}

/// Converts RGBA image data into grayscale-with-alpha.
fn rgba_to_grayalpha(rgba: &[u8]) -> Box<[u8]> {
    assert_eq!(rgba.len() % 4, 0);
    let num_pixels = rgba.len() / 4;
    let mut grayalpha = Vec::with_capacity(num_pixels * 2);
    for i in 0..num_pixels {
        let red = u32::from(rgba[4 * i]);
        let green = u32::from(rgba[4 * i + 1]);
        let blue = u32::from(rgba[4 * i + 2]);
        let alpha = rgba[4 * i + 3];
        grayalpha.push(((red + green + blue) / 3) as u8);
        grayalpha.push(alpha);
    }
    grayalpha.into_boxed_slice()
}

/// Converts RGB image data into grayscale-with-alpha.
fn rgb_to_grayalpha(rgb: &[u8]) -> Box<[u8]> {
    assert_eq!(rgb.len() % 3, 0);
    let num_pixels = rgb.len() / 3;
    let mut gray = Vec::with_capacity(num_pixels);
    for i in 0..num_pixels {
        let red = u32::from(rgb[3 * i]);
        let green = u32::from(rgb[3 * i + 1]);
        let blue = u32::from(rgb[3 * i + 2]);
        gray.push(((red + green + blue) / 3) as u8);
        gray.push(std::u8::MAX);
    }
    gray.into_boxed_slice()
}

/// Converts RGBA image data into an alpha mask.
fn rgba_to_alpha(rgba: &[u8]) -> Box<[u8]> {
    assert_eq!(rgba.len() % 4, 0);
    let num_pixels = rgba.len() / 4;
    let mut alpha = Vec::with_capacity(num_pixels);
    for i in 0..num_pixels {
        alpha.push(rgba[4 * i + 3]);
    }
    alpha.into_boxed_slice()
}

/// Converts RGB image data into an alpha mask.
fn rgb_to_alpha(rgb: &[u8]) -> Box<[u8]> {
    assert_eq!(rgb.len() % 3, 0);
    let num_pixels = rgb.len() / 3;
    vec![std::u8::MAX; num_pixels].into_boxed_slice()
}

/// Converts grayscale-with-alpha image data into RGBA.
fn grayalpha_to_rgba(grayalpha: &[u8]) -> Box<[u8]> {
    assert_eq!(grayalpha.len() % 2, 0);
    let num_pixels = grayalpha.len() / 2;
    let mut rgba = Vec::with_capacity(num_pixels * 4);
    for i in 0..num_pixels {
        let gray = grayalpha[2 * i];
        let alpha = grayalpha[2 * i + 1];
        rgba.push(gray);
        rgba.push(gray);
        rgba.push(gray);
        rgba.push(alpha);
    }
    rgba.into_boxed_slice()
}

/// Converts grayscale-with-alpha image data into RGB.
fn grayalpha_to_rgb(grayalpha: &[u8]) -> Box<[u8]> {
    assert_eq!(grayalpha.len() % 2, 0);
    let num_pixels = grayalpha.len() / 2;
    let mut rgb = Vec::with_capacity(num_pixels * 3);
    for i in 0..num_pixels {
        let gray = grayalpha[2 * i];
        rgb.push(gray);
        rgb.push(gray);
        rgb.push(gray);
    }
    rgb.into_boxed_slice()
}

/// Converts grayscale-with-alpha image data into grayscale-without-alpha.
fn grayalpha_to_gray(grayalpha: &[u8]) -> Box<[u8]> {
    assert_eq!(grayalpha.len() % 2, 0);
    let num_pixels = grayalpha.len() / 2;
    let mut gray = Vec::with_capacity(num_pixels);
    for i in 0..num_pixels {
        let value = grayalpha[2 * i];
        gray.push(value);
    }
    gray.into_boxed_slice()
}

/// Converts grayscale-with-alpha image data into an alpha mask.
fn grayalpha_to_alpha(grayalpha: &[u8]) -> Box<[u8]> {
    assert_eq!(grayalpha.len() % 2, 0);
    let num_pixels = grayalpha.len() / 2;
    let mut alpha = Vec::with_capacity(num_pixels);
    for i in 0..num_pixels {
        let value = grayalpha[2 * i + 1];
        alpha.push(value);
    }
    alpha.into_boxed_slice()
}

/// Converts grayscale image data into RGBA.
fn gray_to_rgba(gray: &[u8]) -> Box<[u8]> {
    let num_pixels = gray.len();
    let mut rgba = Vec::with_capacity(num_pixels * 4);
    for &value in gray {
        rgba.push(value);
        rgba.push(value);
        rgba.push(value);
        rgba.push(std::u8::MAX);
    }
    rgba.into_boxed_slice()
}

/// Converts grayscale image data into RGB.
fn gray_to_rgb(gray: &[u8]) -> Box<[u8]> {
    let num_pixels = gray.len();
    let mut rgb = Vec::with_capacity(num_pixels * 3);
    for &value in gray {
        rgb.push(value);
        rgb.push(value);
        rgb.push(value);
    }
    rgb.into_boxed_slice()
}

/// Converts grayscale image data into grayscale-with-alpha.
fn gray_to_grayalpha(gray: &[u8]) -> Box<[u8]> {
    let num_pixels = gray.len();
    let mut grayalpha = Vec::with_capacity(num_pixels * 2);
    for &value in gray {
        grayalpha.push(value);
        grayalpha.push(std::u8::MAX);
    }
    grayalpha.into_boxed_slice()
}

/// Converts grayscale image data into an alpha mask.
fn gray_to_alpha(gray: &[u8]) -> Box<[u8]> {
    vec![std::u8::MAX; gray.len()].into_boxed_slice()
}

/// Converts alpha mask image data into RGBA.
fn alpha_to_rgba(alpha: &[u8]) -> Box<[u8]> {
    let num_pixels = alpha.len();
    let mut rgba = Vec::with_capacity(num_pixels * 4);
    for &value in alpha {
        rgba.push(0);
        rgba.push(0);
        rgba.push(0);
        rgba.push(value);
    }
    rgba.into_boxed_slice()
}

/// Converts alpha mask image data into RGB.
fn alpha_to_rgb(alpha: &[u8]) -> Box<[u8]> {
    vec![0u8; alpha.len() * 3].into_boxed_slice()
}

/// Converts alpha mask image data into grayscale-with-alpha.
fn alpha_to_grayalpha(alpha: &[u8]) -> Box<[u8]> {
    let num_pixels = alpha.len();
    let mut grayalpha = Vec::with_capacity(num_pixels * 2);
    for &value in alpha {
        grayalpha.push(0);
        grayalpha.push(value);
    }
    grayalpha.into_boxed_slice()
}

/// Converts alpha mask image data into grayscale.
fn alpha_to_gray(alpha: &[u8]) -> Box<[u8]> {
    vec![0u8; alpha.len()].into_boxed_slice()
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Cursor;

    #[test]
    fn image_from_data() {
        let data: Vec<u8> = vec![255, 0, 0, 0, 255, 0, 0, 0, 255, 95, 95, 95];
        let image = Image::from_data(PixelFormat::RGB, 2, 2, data.clone()).unwrap();
        assert_eq!(image.data(), &data as &[u8]);
    }

    #[test]
    fn image_from_data_wrong_size() {
        let data: Vec<u8> = vec![1, 2, 3];
        let result = Image::from_data(PixelFormat::Alpha, 2, 2, data);
        assert!(result.is_err());
    }

    #[test]
    fn alpha_to_gray() {
        let alpha_data: Vec<u8> = vec![63, 127, 191, 255];
        let mut alpha_image = Image::new(PixelFormat::Alpha, 2, 2);
        alpha_image.data_mut().clone_from_slice(&alpha_data);
        let gray_image = alpha_image.convert_to(PixelFormat::Gray);
        let gray_data: Vec<u8> = vec![0, 0, 0, 0];
        assert_eq!(gray_image.data(), &gray_data as &[u8]);
    }

    #[test]
    fn alpha_to_grayalpha() {
        let alpha_data: Vec<u8> = vec![63, 127, 191, 255];
        let mut alpha_image = Image::new(PixelFormat::Alpha, 2, 2);
        alpha_image.data_mut().clone_from_slice(&alpha_data);
        let grayalpha_image = alpha_image.convert_to(PixelFormat::GrayAlpha);
        let grayalpha_data: Vec<u8> = vec![0, 63, 0, 127, 0, 191, 0, 255];
        assert_eq!(grayalpha_image.data(), &grayalpha_data as &[u8]);
    }

    #[test]
    fn alpha_to_rgb() {
        let alpha_data: Vec<u8> = vec![63, 127, 191, 255];
        let mut alpha_image = Image::new(PixelFormat::Alpha, 2, 2);
        alpha_image.data_mut().clone_from_slice(&alpha_data);
        let rgb_image = alpha_image.convert_to(PixelFormat::RGB);
        let rgb_data: Vec<u8> = vec![0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
        assert_eq!(rgb_image.data(), &rgb_data as &[u8]);
    }

    #[test]
    fn alpha_to_rgba() {
        let alpha_data: Vec<u8> = vec![63, 127, 191, 255];
        let mut alpha_image = Image::new(PixelFormat::Alpha, 2, 2);
        alpha_image.data_mut().clone_from_slice(&alpha_data);
        let rgba_image = alpha_image.convert_to(PixelFormat::RGBA);
        let rgba_data: Vec<u8> = vec![0, 0, 0, 63, 0, 0, 0, 127, 0, 0, 0, 191, 0, 0, 0, 255];
        assert_eq!(rgba_image.data(), &rgba_data as &[u8]);
    }

    #[test]
    fn gray_to_alpha() {
        let gray_data: Vec<u8> = vec![63, 127, 191, 255];
        let mut gray_image = Image::new(PixelFormat::Gray, 2, 2);
        gray_image.data_mut().clone_from_slice(&gray_data);
        let alpha_image = gray_image.convert_to(PixelFormat::Alpha);
        let alpha_data: Vec<u8> = vec![255, 255, 255, 255];
        assert_eq!(alpha_image.data(), &alpha_data as &[u8]);
    }

    #[test]
    fn gray_to_grayalpha() {
        let gray_data: Vec<u8> = vec![63, 127, 191, 255];
        let mut gray_image = Image::new(PixelFormat::Gray, 2, 2);
        gray_image.data_mut().clone_from_slice(&gray_data);
        let grayalpha_image = gray_image.convert_to(PixelFormat::GrayAlpha);
        let grayalpha_data: Vec<u8> = vec![63, 255, 127, 255, 191, 255, 255, 255];
        assert_eq!(grayalpha_image.data(), &grayalpha_data as &[u8]);
    }

    #[test]
    fn gray_to_rgb() {
        let gray_data: Vec<u8> = vec![63, 127, 191, 255];
        let mut gray_image = Image::new(PixelFormat::Gray, 2, 2);
        gray_image.data_mut().clone_from_slice(&gray_data);
        let rgb_image = gray_image.convert_to(PixelFormat::RGB);
        let rgb_data: Vec<u8> = vec![63, 63, 63, 127, 127, 127, 191, 191, 191, 255, 255, 255];
        assert_eq!(rgb_image.data(), &rgb_data as &[u8]);
    }

    #[test]
    fn gray_to_rgba() {
        let gray_data: Vec<u8> = vec![63, 127, 191, 255];
        let mut gray_image = Image::new(PixelFormat::Gray, 2, 2);
        gray_image.data_mut().clone_from_slice(&gray_data);
        let rgba_image = gray_image.convert_to(PixelFormat::RGBA);
        assert_eq!(rgba_image.pixel_format(), PixelFormat::RGBA);
        assert_eq!(rgba_image.width(), 2);
        assert_eq!(rgba_image.height(), 2);
        let rgba_data: Vec<u8> = vec![
            63, 63, 63, 255, 127, 127, 127, 255, 191, 191, 191, 255, 255, 255, 255, 255,
        ];
        assert_eq!(rgba_image.data(), &rgba_data as &[u8]);
    }

    #[test]
    fn grayalpha_to_alpha() {
        let grayalpha_data: Vec<u8> = vec![1, 2, 3, 4, 5, 6, 7, 8];
        let mut grayalpha_image = Image::new(PixelFormat::GrayAlpha, 2, 2);
        grayalpha_image.data_mut().clone_from_slice(&grayalpha_data);
        let alpha_image = grayalpha_image.convert_to(PixelFormat::Alpha);
        let alpha_data: Vec<u8> = vec![2, 4, 6, 8];
        assert_eq!(alpha_image.data(), &alpha_data as &[u8]);
    }

    #[test]
    fn grayalpha_to_gray() {
        let grayalpha_data: Vec<u8> = vec![1, 2, 3, 4, 5, 6, 7, 8];
        let mut grayalpha_image = Image::new(PixelFormat::GrayAlpha, 2, 2);
        grayalpha_image.data_mut().clone_from_slice(&grayalpha_data);
        let gray_image = grayalpha_image.convert_to(PixelFormat::Gray);
        let gray_data: Vec<u8> = vec![1, 3, 5, 7];
        assert_eq!(gray_image.data(), &gray_data as &[u8]);
    }

    #[test]
    fn grayalpha_to_rgb() {
        let grayalpha_data: Vec<u8> = vec![1, 2, 3, 4, 5, 6, 7, 8];
        let mut grayalpha_image = Image::new(PixelFormat::GrayAlpha, 2, 2);
        grayalpha_image.data_mut().clone_from_slice(&grayalpha_data);
        let rgb_image = grayalpha_image.convert_to(PixelFormat::RGB);
        let rgb_data: Vec<u8> = vec![1, 1, 1, 3, 3, 3, 5, 5, 5, 7, 7, 7];
        assert_eq!(rgb_image.data(), &rgb_data as &[u8]);
    }

    #[test]
    fn grayalpha_to_rgba() {
        let grayalpha_data: Vec<u8> = vec![1, 2, 3, 4, 5, 6, 7, 8];
        let mut grayalpha_image = Image::new(PixelFormat::GrayAlpha, 2, 2);
        grayalpha_image.data_mut().clone_from_slice(&grayalpha_data);
        let rgba_image = grayalpha_image.convert_to(PixelFormat::RGBA);
        let rgba_data: Vec<u8> = vec![1, 1, 1, 2, 3, 3, 3, 4, 5, 5, 5, 6, 7, 7, 7, 8];
        assert_eq!(rgba_image.data(), &rgba_data as &[u8]);
    }

    #[test]
    fn rgb_to_alpha() {
        let rgb_data: Vec<u8> = vec![30, 0, 0, 0, 60, 0, 0, 0, 90, 40, 40, 40];
        let mut rgb_image = Image::new(PixelFormat::RGB, 2, 2);
        rgb_image.data_mut().clone_from_slice(&rgb_data);
        let alpha_image = rgb_image.convert_to(PixelFormat::Alpha);
        let alpha_data: Vec<u8> = vec![255, 255, 255, 255];
        assert_eq!(alpha_image.data(), &alpha_data as &[u8]);
    }

    #[test]
    fn rgb_to_gray() {
        let rgb_data: Vec<u8> = vec![30, 0, 0, 0, 60, 0, 0, 0, 90, 40, 40, 40];
        let mut rgb_image = Image::new(PixelFormat::RGB, 2, 2);
        rgb_image.data_mut().clone_from_slice(&rgb_data);
        let gray_image = rgb_image.convert_to(PixelFormat::Gray);
        let gray_data: Vec<u8> = vec![10, 20, 30, 40];
        assert_eq!(gray_image.data(), &gray_data as &[u8]);
    }

    #[test]
    fn rgb_to_grayalpha() {
        let rgb_data: Vec<u8> = vec![30, 0, 0, 0, 60, 0, 0, 0, 90, 40, 40, 40];
        let mut rgb_image = Image::new(PixelFormat::RGB, 2, 2);
        rgb_image.data_mut().clone_from_slice(&rgb_data);
        let grayalpha_image = rgb_image.convert_to(PixelFormat::GrayAlpha);
        let grayalpha_data: Vec<u8> = vec![10, 255, 20, 255, 30, 255, 40, 255];
        assert_eq!(grayalpha_image.data(), &grayalpha_data as &[u8]);
    }

    #[test]
    fn rgb_to_rgba() {
        let rgb_data: Vec<u8> = vec![255, 0, 0, 0, 255, 0, 0, 0, 255, 127, 127, 127];
        let mut rgb_image = Image::new(PixelFormat::RGB, 2, 2);
        rgb_image.data_mut().clone_from_slice(&rgb_data);
        let rgba_image = rgb_image.convert_to(PixelFormat::RGBA);
        assert_eq!(rgba_image.pixel_format(), PixelFormat::RGBA);
        assert_eq!(rgba_image.width(), 2);
        assert_eq!(rgba_image.height(), 2);
        let rgba_data: Vec<u8> = vec![
            255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 127, 127, 127, 255,
        ];
        assert_eq!(rgba_image.data(), &rgba_data as &[u8]);
    }

    #[test]
    fn rgba_to_alpha() {
        let rgba_data: Vec<u8> = vec![30, 0, 0, 200, 0, 60, 0, 150, 0, 0, 90, 100, 40, 40, 40, 50];
        let mut rgba_image = Image::new(PixelFormat::RGBA, 2, 2);
        rgba_image.data_mut().clone_from_slice(&rgba_data);
        let alpha_image = rgba_image.convert_to(PixelFormat::Alpha);
        let alpha_data: Vec<u8> = vec![200, 150, 100, 50];
        assert_eq!(alpha_image.data(), &alpha_data as &[u8]);
    }

    #[test]
    fn rgba_to_gray() {
        let rgba_data: Vec<u8> = vec![30, 0, 0, 200, 0, 60, 0, 150, 0, 0, 90, 100, 40, 40, 40, 50];
        let mut rgba_image = Image::new(PixelFormat::RGBA, 2, 2);
        rgba_image.data_mut().clone_from_slice(&rgba_data);
        let gray_image = rgba_image.convert_to(PixelFormat::Gray);
        let gray_data: Vec<u8> = vec![10, 20, 30, 40];
        assert_eq!(gray_image.data(), &gray_data as &[u8]);
    }

    #[test]
    fn rgba_to_grayalpha() {
        let rgba_data: Vec<u8> = vec![30, 0, 0, 200, 0, 60, 0, 150, 0, 0, 90, 100, 40, 40, 40, 50];
        let mut rgba_image = Image::new(PixelFormat::RGBA, 2, 2);
        rgba_image.data_mut().clone_from_slice(&rgba_data);
        let grayalpha_image = rgba_image.convert_to(PixelFormat::GrayAlpha);
        let grayalpha_data: Vec<u8> = vec![10, 200, 20, 150, 30, 100, 40, 50];
        assert_eq!(grayalpha_image.data(), &grayalpha_data as &[u8]);
    }

    #[test]
    fn rgba_to_rgb() {
        let rgba_data: Vec<u8> = vec![30, 0, 0, 200, 0, 60, 0, 150, 0, 0, 90, 100, 40, 40, 40, 50];
        let mut rgba_image = Image::new(PixelFormat::RGBA, 2, 2);
        rgba_image.data_mut().clone_from_slice(&rgba_data);
        let rgb_image = rgba_image.convert_to(PixelFormat::RGB);
        let rgb_data: Vec<u8> = vec![30, 0, 0, 0, 60, 0, 0, 0, 90, 40, 40, 40];
        assert_eq!(rgb_image.data(), &rgb_data as &[u8]);
    }

    #[test]
    #[cfg(feature = "pngio")]
    fn write_grayscale_png() {
        let gray_data: Vec<u8> = vec![63, 127, 191, 255];
        let mut image = Image::new(PixelFormat::Gray, 2, 2);
        image.data_mut().clone_from_slice(&gray_data);
        let mut output: Vec<u8> = Vec::new();
        image.write_png(&mut output).expect("failed to write PNG");
        let expected: Vec<u8> = vec![
            137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 2, 0, 0, 0, 2,
            8, 0, 0, 0, 0, 87, 221, 82, 248, 0, 0, 0, 14, 73, 68, 65, 84, 120, 156, 99, 180, 119,
            96, 220, 239, 0, 0, 4, 8, 1, 129, 134, 46, 201, 141, 0, 0, 0, 0, 73, 69, 78, 68, 174,
            66, 96, 130,
        ];
        assert_eq!(output, expected);
    }

    #[test]
    #[cfg(feature = "pngio")]
    fn write_rgb_png() {
        let rgb_data: Vec<u8> = vec![255, 0, 0, 0, 255, 0, 0, 0, 255, 127, 127, 127];
        let mut image = Image::new(PixelFormat::RGB, 2, 2);
        image.data_mut().clone_from_slice(&rgb_data);
        let mut output: Vec<u8> = Vec::new();
        image.write_png(&mut output).expect("failed to write PNG");
        let expected: Vec<u8> = vec![
            137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 2, 0, 0, 0, 2,
            8, 2, 0, 0, 0, 253, 212, 154, 115, 0, 0, 0, 20, 73, 68, 65, 84, 120, 156, 99, 252, 207,
            192, 0, 196, 140, 12, 12, 255, 235, 235, 27, 0, 29, 14, 4, 127, 253, 15, 140, 153, 0,
            0, 0, 0, 73, 69, 78, 68, 174, 66, 96, 130,
        ];
        assert_eq!(output, expected);
    }

    #[test]
    #[cfg(feature = "pngio")]
    fn write_rgba_png() {
        let rgba_data: Vec<u8> = vec![
            255, 0, 0, 63, 0, 255, 0, 127, 0, 0, 255, 191, 127, 127, 127, 255,
        ];
        let mut image = Image::new(PixelFormat::RGBA, 2, 2);
        image.data_mut().clone_from_slice(&rgba_data);
        let mut output: Vec<u8> = Vec::new();
        image.write_png(&mut output).expect("failed to write PNG");
        let expected: Vec<u8> = vec![
            137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 2, 0, 0, 0, 2,
            8, 6, 0, 0, 0, 114, 182, 13, 36, 0, 0, 0, 25, 73, 68, 65, 84, 120, 156, 99, 252, 207,
            192, 96, 15, 36, 28, 24, 25, 24, 254, 239, 175, 175, 111, 112, 0, 0, 49, 125, 5, 253,
            88, 193, 178, 240, 0, 0, 0, 0, 73, 69, 78, 68, 174, 66, 96, 130,
        ];
        assert_eq!(output, expected);
    }

    #[test]
    #[cfg(feature = "pngio")]
    fn read_rgba_png() {
        let png: Vec<u8> = vec![
            137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 2, 0, 0, 0, 2,
            8, 6, 0, 0, 0, 114, 182, 13, 36, 0, 0, 0, 29, 73, 68, 65, 84, 120, 1, 1, 18, 0, 237,
            255, 1, 255, 0, 0, 63, 1, 255, 0, 64, 1, 0, 0, 255, 191, 127, 127, 128, 64, 49, 125, 5,
            253, 198, 70, 247, 56, 0, 0, 0, 0, 73, 69, 78, 68, 174, 66, 96, 130,
        ];
        let image = Image::read_png(Cursor::new(&png)).expect("failed to read PNG");
        assert_eq!(image.data(), &png as &[u8]);
        let image = image.convert_to(PixelFormat::RGBA);
        assert_eq!(image.pixel_format(), PixelFormat::RGBA);
        assert_eq!(image.width(), 2);
        assert_eq!(image.height(), 2);
        let rgba_data: Vec<u8> = vec![
            255, 0, 0, 63, 0, 255, 0, 127, 0, 0, 255, 191, 127, 127, 127, 255,
        ];
        assert_eq!(image.data(), &rgba_data as &[u8]);
    }

    #[test]
    #[cfg(feature = "pngio")]
    fn png_round_trip() {
        let rgba_data: Vec<u8> = vec![
            127, 0, 0, 63, 0, 191, 0, 127, 0, 0, 255, 191, 127, 127, 127, 255,
        ];
        let mut rgba_image = Image::new(PixelFormat::RGBA, 2, 2);
        rgba_image.data_mut().clone_from_slice(&rgba_data);
        let pixel_formats = [
            PixelFormat::RGBA,
            PixelFormat::RGB,
            PixelFormat::GrayAlpha,
            PixelFormat::Gray,
            PixelFormat::Alpha,
        ];
        for &format in pixel_formats.iter() {
            // For each pixel format, try writing a PNG from an image in that
            // format.
            let image_1 = rgba_image.convert_to(format);
            let mut png_data = Vec::<u8>::new();
            image_1
                .write_png(&mut png_data)
                .expect("failed to write PNG");
            // We should be able to read the PNG back in successfully.
            let mut image_2 = Image::read_png(Cursor::new(&png_data)).expect("failed to read PNG");
            // We may get the image back in a different pixel format.  However,
            // in such cases we should be able to convert back to the original
            // pixel format and still get back exactly the same data.
            if image_2.pixel_format() != image_1.pixel_format() {
                image_2 = image_2.convert_to(image_1.pixel_format());
            }
            assert_eq!(image_1.data(), image_2.data());
        }
    }
}