pixtra 0.2.2

Pixtra aims to be a very simple and easy-to-use image manipulation tool by being opionated and contain a lot of examples
Documentation
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
use crate::pixels::{ColorTrait, Colors, Pixel};
use crate::utility::{clamp, overlap_colors, to_grey_lumiosity};
use image::{GenericImageView, ImageFormat, RgbaImage};
use std::cmp::{max, min};
use std::fmt;
use std::path::Path;

//TODO: Should I use u32 or usize? Rely on image crate?
//
//
//TODO!!!! Make use of Point and Box for get_pixel and get_subimage
//TODO!!!! Create documentation so you can utilize it in this project

#[derive(Clone, Debug)]
pub struct Canvas {
    pixels: Vec<Pixel>,
    height: u32,
    width: u32,
}

#[derive(Clone, Debug)]
pub struct Point {
    pub x: u32,
    pub y: u32,
}

#[derive(Clone, Debug)]
pub struct PixelWithCoordinate {
    pub coordinate: Point,
    pub pixel: Pixel,
}

#[derive(Clone, Debug)]
pub struct Size {
    pub width: u32,
    pub height: u32,
}

#[derive(Clone, Debug)]
pub struct Rect {
    pub start: Point,
    pub size: Size,
}

#[derive(Debug)]
pub enum ImageError {
    Decoding(String),
    Encoding(String),
    Parameter(String),
    Limits(String),
    Unsupported(String),
    IoError(String),
}

impl PartialEq for Size {
    fn eq(&self, other: &Self) -> bool {
        self.width == other.width && self.height == other.height
    }
}

impl Eq for Size {}

impl PartialEq for Canvas {
    fn eq(&self, other: &Self) -> bool {
        if self.width == other.width && self.height == other.height {
            let result = self
                .pixels
                .iter()
                .zip(other.pixels.iter())
                .fold(true, |acc, (left, right)| acc && left == right);
            return result;
        }
        false
    }
}
impl Eq for Canvas {}

// TODO!
impl fmt::Display for Canvas {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "Image with {} pixels and dimensions: ({}, {}).",
            self.pixels.len(),
            self.width,
            self.height
        )
    }
}

// TODO: IoError should be descriptive of which file you are trying to open.
fn map_error(error: &image::ImageError) -> ImageError {
    match error {
        image::ImageError::Decoding(e) => {
            return ImageError::Decoding(e.to_string());
        }
        image::ImageError::Encoding(e) => {
            return ImageError::Encoding(e.to_string());
        }
        image::ImageError::Parameter(e) => {
            return ImageError::Parameter(e.to_string());
        }
        image::ImageError::Limits(e) => {
            return ImageError::Limits(e.to_string());
        }
        image::ImageError::Unsupported(e) => {
            return ImageError::Unsupported(e.to_string());
        }
        image::ImageError::IoError(e) => {
            return ImageError::IoError(e.to_string());
        }
    }
}

impl Canvas {
    /// Create a new `Canvas` of size `width` and `height`
    ///
    /// # Examples
    ///
    /// ```
    /// use pixtra::canvas::Canvas;
    ///
    /// let canvas = Canvas::new(20, 20);
    /// ```
    /// For more examples look at examples (examples/create-image.rs)
    pub fn new(width: u32, height: u32) -> Canvas {
        let width = max(width, 1);
        let height = max(height, 1);
        let pixels = vec![Colors::WHITE; (width * height) as usize];
        Canvas {
            pixels,
            height,
            width,
        }
    }

    /// Creates a new `Canvas` of size `width` and `height` with initial data of `data`
    // TODO: Make it so that we align size of `data` to align with `width*height`.
    pub fn new_with_data(width: u32, height: u32, data: Vec<Pixel>) -> Canvas {
        Canvas {
            width,
            height,
            pixels: data,
        }
    }

    /// Retrieves width and height of canvas in a `Size` struct.
    pub fn dimensions(&self) -> Size {
        Size {
            width: self.width,
            height: self.height,
        }
    }

    /// Returns an iterator for all the pixels in the `Canvas`.
    // TODO: Should this return the positions of the pixels as well or do we want a utility
    // function for that?
    pub fn pixels(&self) -> std::slice::Iter<'_, Pixel> {
        self.pixels.iter()
    }

    /// Creates a new `Canvas` of size `width` and `height` with all pixels initially set to
    /// `color`.
    pub fn new_with_background(width: u32, height: u32, color: Pixel) -> Canvas {
        let width = max(width, 1);
        let height = max(height, 1);
        let pixels = vec![color; (width * height) as usize];
        Canvas {
            pixels,
            height,
            width,
        }
    }

    /// Saves the canvas as an image at the path given by `filename`
    pub fn save(&self, filename: &Path) -> Result<(), ImageError> {
        let img = RgbaImage::from_vec(
            self.width,
            self.height,
            self.pixels
                .iter()
                .flat_map(|x| vec![x.r, x.g, x.b, x.a])
                .collect(),
        );

        match img {
            Some(image) => {
                let res = image.save_with_format(filename, ImageFormat::Png);
                match res {
                    Ok(_) => {
                        return Ok(());
                    }
                    Err(e) => {
                        return Err(map_error(&e));
                    }
                }
            }
            None => {
                // TODO: What to return here?
                return Ok(());
            }
        }
    }

    /// Loads the image at the path given by `filename` and returns it as a canvas
    pub fn load(filename: &Path) -> Result<Canvas, ImageError> {
        let img = image::open(filename);
        match img {
            Ok(image) => {
                let (width, height) = image.dimensions();
                let mut vec = vec![Colors::WHITE; (width * height) as usize];
                for (x, y, pixel) in image.pixels() {
                    vec[(width * y + x) as usize] = Pixel {
                        r: pixel[0],
                        g: pixel[1],
                        b: pixel[2],
                        a: pixel[3],
                    }
                }
                return Ok(Canvas {
                    pixels: vec,
                    height,
                    width,
                });
            }
            Err(e) => {
                return Err(map_error(&e));
            }
        }
    }

    /// Counts the amount of pixels in the canvas equal to `pixel`
    pub fn count_pixels(&self, pixel: &Pixel) -> u32 {
        self.find_positions_of_pixels(pixel).len() as u32
    }

    /// Counts the amount of pixels in the canvas that are within the distance of `distance` of
    /// `pixel`
    pub fn count_pixels_with_distance(&self, pixel: &Pixel, distance: f32) -> u32 {
        self.find_positions_of_pixels_with_distance(pixel, distance)
            .len() as u32
    }

    fn find_positions_of_pixels(&self, pixel: &Pixel) -> Vec<usize> {
        self.pixels
            .iter()
            .enumerate()
            .filter(|(_, val)| val == &pixel)
            .map(|(i, _)| i)
            .collect()
    }

    fn find_positions_of_pixels_with_distance(&self, pixel: &Pixel, distance: f32) -> Vec<usize> {
        self.pixels
            .iter()
            .enumerate()
            .filter(|(_, val)| pixel.distance(&val) < distance)
            .map(|(i, _)| i)
            .collect()
    }

    /// Replaces all pixels in the canvas that are within the distance of `distance` of `pixel`
    pub fn replace_pixel_with_distance(
        mut self,
        find_pixel: &Pixel,
        distance: f32,
        replace_pixel: &Pixel,
    ) -> Canvas {
        let positions = self.find_positions_of_pixels_with_distance(find_pixel, distance);
        for pos in positions {
            self.pixels[pos] = replace_pixel.clone();
        }

        self
    }

    /// Replaces all pixels in the canvas that are within the distance of `distance` of `pixel`
    pub fn replace_pixel_with_distance_mut(
        &mut self,
        find_pixel: &Pixel,
        distance: f32,
        replace_pixel: &Pixel,
    ) {
        let positions = self.find_positions_of_pixels_with_distance(find_pixel, distance);
        for pos in positions {
            self.pixels[pos] = replace_pixel.clone();
        }
    }

    /// Replaces all pixels in the canvas that are equal to `pixel`
    pub fn replace_pixel_with(mut self, find_pixel: &Pixel, replace_pixel: &Pixel) -> Canvas {
        let positions = self.find_positions_of_pixels(find_pixel);
        for pos in positions {
            self.pixels[pos] = replace_pixel.clone();
        }

        self
    }

    /// Replaces all pixels in the canvas that are equal to `pixel`
    pub fn replace_pixel_with_mut(&mut self, find_pixel: &Pixel, replace_pixel: &Pixel) {
        let positions = self.find_positions_of_pixels(find_pixel);
        for pos in positions {
            self.pixels[pos] = replace_pixel.clone();
        }
    }

    /// Returns a canvas that is subimage starting at `(x, y)` with size `width x height`.
    pub fn get_subimage(&self, x: u32, y: u32, width: u32, height: u32) -> Canvas {
        let width = min(width, self.width - x);
        let height = min(height, self.height - y);

        let mut c = Canvas::new(width, height);
        for i in 0..width {
            for j in 0..height {
                c.set_pixel_mut(i, j, &self.get_pixel(x + i, y + j));
            }
        }
        c
    }

    pub fn draw_subimage_mut(&mut self, x: u32, y: u32, canvas: &Canvas) {
        //TODO: Stop replicating this code
        let width = min(canvas.width, self.width - x);
        let height = min(canvas.height, self.height - y);
        //TODO: Create iterator
        for i in 0..width {
            for j in 0..height {
                let destination = self.get_pixel(x + i, y + j);
                let source = canvas.get_pixel(i, j);
                let new_color = overlap_colors(&destination, &source);
                self.set_pixel_mut(x + i, y + j, &new_color);
            }
        }
    }

    /// Inserts canvas `canvas` as a subimage at `(x, y)`
    pub fn set_subimage_mut(&mut self, x: u32, y: u32, canvas: &Canvas) {
        let width = min(canvas.width, self.width - x);
        let height = min(canvas.height, self.height - y);
        for i in 0..width {
            for j in 0..height {
                self.set_pixel_mut(x + i, y + j, &canvas.get_pixel(i, j));
            }
        }
    }

    pub fn draw_subimage(mut self, x: u32, y: u32, canvas: &Canvas) -> Canvas {
        let width = min(canvas.width, self.width - x);
        let height = min(canvas.height, self.height - y);
        for i in 0..width {
            for j in 0..height {
                let destination = self.get_pixel(x + i, y + j);
                let source = canvas.get_pixel(i, j);
                let new_color = overlap_colors(&destination, &source);
                self.set_pixel_mut(x + i, y + j, &new_color);
            }
        }
        self
    }

    /// Inserts canvas `canvas` as a subimage at `(x, y)`
    pub fn set_subimage(mut self, x: u32, y: u32, c: &Canvas) -> Canvas {
        let width = min(c.width, self.width - x);
        let height = min(c.height, self.height - y);
        for i in 0..width {
            for j in 0..height {
                self.set_pixel_mut(x + i, y + j, &c.get_pixel(i, j));
            }
        }
        self
    }

    /// Returns pixel at position `(x, y)` from the canvas
    pub fn get_pixel(&self, x: u32, y: u32) -> Pixel {
        let x = clamp(0, self.width - 1, x);
        let y = clamp(0, self.height - 1, y);
        let pixel = self.pixels[(self.width * y + x) as usize].clone();
        pixel
    }

    /// Sets pixel at position `(x, y)` to `pixel`
    pub fn set_pixel(mut self, x: u32, y: u32, pixel: &Pixel) -> Canvas {
        self.pixels[(self.width * y + x) as usize] = pixel.clone();
        self
    }

    /// Sets pixel at position `(x, y)` to `pixel`
    pub fn set_pixel_mut(&mut self, x: u32, y: u32, pixel: &Pixel) {
        self.pixels[(self.width * y + x) as usize] = pixel.clone();
    }

    /// Turns the entire canvas grayscale.
    pub fn to_grey(&self) -> Canvas {
        let pixels = self.pixels.iter().map(|x| to_grey_lumiosity(x)).collect();
        Canvas {
            pixels,
            height: self.height,
            width: self.width,
        }
    }

    /// Turns the entire canvas grayscale.
    pub fn to_grey_mut(&mut self) {
        let pixels = self.pixels.iter().map(|x| to_grey_lumiosity(x)).collect();
        self.pixels = pixels;
    }

    /// Draws a square on the canvas. Draws at position `(x, y)` with size `width x height`. Color
    /// is `color`.
    pub fn draw_square_mut(&mut self, x: u32, y: u32, w: u32, h: u32, color: &Pixel) {
        if x < self.width && y < self.height {
            for i in x..min(x + w, self.width) {
                for j in y..min(y + h, self.height) {
                    let current_color = &self.get_pixel(i, j);
                    //TODO: RENAME
                    let new_color = overlap_colors(&current_color, &color);
                    self.set_pixel_mut(i, j, &new_color);
                }
            }
        }
    }

    /// Draws a square on the canvas. Draws at position `(x, y)` with size `width x height`. Color
    /// is `color`.
    pub fn draw_square(mut self, x: u32, y: u32, w: u32, h: u32, color: &Pixel) -> Canvas {
        if x < self.width && y < self.height {
            for i in x..min(x + w, self.width) {
                for j in y..min(y + h, self.height) {
                    let current_color = &self.get_pixel(i, j);
                    let new_color = overlap_colors(&current_color, &color);
                    self.set_pixel_mut(i, j, &new_color);
                }
            }
        }
        self
    }

    // By orlp
    fn in_bounds(&self, x: i64, y: i64) -> bool {
        x >= 0 && x < self.width.into() && y >= 0 && y < self.height.into()
    }

    // By orlp
    fn try_get_pixel(&self, x: i64, y: i64) -> Option<&Pixel> {
        self.in_bounds(x, y)
            .then(|| &self.pixels[(self.width as i64 * y + x) as usize])
    }

    // By orlp
    pub fn fill(mut self, x: u32, y: u32, fill_color: &Pixel) -> Canvas {
        let find_color = self.get_pixel(x, y);
        if fill_color == &find_color {
            return self;
        }

        let mut to_visit = vec![(x as i64, y as i64)];
        while let Some((x, y)) = to_visit.pop() {
            self.set_pixel_mut(x as u32, y as u32, fill_color);

            for (dx, dy) in [(-1, 0), (1, 0), (0, -1), (0, 1)] {
                if self.try_get_pixel(x + dx, y + dy) == Some(&find_color) {
                    to_visit.push((x + dx, y + dy));
                }
            }
        }

        self
    }

    /// Applies filter to entire canvas. `filter` is a function that takes a reference to the
    /// canvas and position `(x, y)` and returns the color which should be set at that position.
    pub fn filter(&self, filter: fn(&Canvas, u32, u32) -> Pixel) -> Canvas {
        let mut canvas = Canvas::new(self.width, self.height);
        for x in 0..self.width {
            for y in 0..self.height {
                let pixel = filter(&self, x, y);
                canvas.set_pixel_mut(x, y, &pixel);
            }
        }
        canvas
    }

    pub fn find_with_predicate(
        &self,
        predicate: fn(&Pixel, u32, u32) -> bool,
    ) -> Vec<PixelWithCoordinate> {
        let mut vec = Vec::new();
        //TODO: Create iterator
        for i in 0..self.width {
            for j in 0..self.height {
                if predicate(&self.get_pixel(i, j), i, j) {
                    let p = PixelWithCoordinate {
                        coordinate: Point { x: i, y: j },
                        pixel: self.get_pixel(i, j).clone(),
                    };
                    vec.push(p);
                }
            }
        }
        vec
    }

    // TODO: What is the opionated solution to this that fits into tiles?
    // If a user calls this to get something that exceeds width and height?
    /*pub fn get_subimage(&self, x: u32, y: u32, w: u32, h: u32) -> Canvas {


    }*/

    /// Flips the image on the vertical axis
    pub fn flip(&self) -> Canvas {
        let mut reversed = Vec::with_capacity(self.width as usize * self.height as usize);
        for pixels in self.pixels.chunks(self.width as usize) {
            let rev: Vec<Pixel> = pixels.iter().rev().map(|x| x.to_owned()).collect();
            reversed.extend(rev);
        }
        Canvas {
            pixels: reversed,
            width: self.width,
            height: self.height,
        }
    }

    /// Flips the image on the horizontal axis
    pub fn flop(&self) -> Canvas {
        let reversed = self.pixels.iter().rev().map(|x| x.to_owned()).collect();

        let canvas = Canvas {
            pixels: reversed,
            width: self.width,
            height: self.height,
        };
        let flipped = canvas.flip();
        flipped
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::pixels::Pixel;
    use crate::utility::count_colors;

    #[test]
    fn clean_canvas() {
        let canvas = Canvas::new(20, 20);
        let dimensions = canvas.dimensions();
        assert_eq!(
            dimensions,
            Size {
                width: 20,
                height: 20
            }
        );

        let counts = count_colors(&canvas);
        assert_eq!(counts.keys().len(), 1);
        assert_eq!(counts.get(&Pixel::new(255, 255, 255, 255)), Some(&400));
    }

    #[test]
    fn clean_canvas_with_background() {
        let color = Pixel::random();
        let canvas = Canvas::new_with_background(20, 20, color.clone());
        let dimensions = canvas.dimensions();
        assert_eq!(
            dimensions,
            Size {
                width: 20,
                height: 20
            }
        );

        let counts = count_colors(&canvas);
        assert_eq!(counts.keys().len(), 1);
        assert_eq!(counts.get(&color), Some(&400));
    }
}