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
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
//! Image transformations, ie: scale, crop, resize, etc.,

use crate::helpers;
use crate::iter::ImageIterator;
use crate::{PhotonImage, Rgba};
use image::imageops::FilterType;
use image::DynamicImage::ImageRgba8;
use image::RgbaImage;
use image::{GenericImageView, ImageBuffer};
use std::cmp::max;
use std::cmp::min;
use wasm_bindgen::prelude::*;

#[cfg(target_arch = "wasm32")]
use wasm_bindgen::{Clamped, JsCast};
#[cfg(target_arch = "wasm32")]
use web_sys::{HtmlCanvasElement, ImageData};

/// Crop an image.
///
/// # Arguments
/// * `img` - A PhotonImage.
///
/// # Example
///
/// ```no_run
/// // For example, to crop an image at (0, 0) to (500, 800)
/// use photon_rs::native::{open_image};
/// use photon_rs::transform::crop;
/// use photon_rs::PhotonImage;
///
/// let mut img = open_image("img.jpg").expect("File should open");
/// let cropped_img: PhotonImage = crop(&mut img, 0_u32, 0_u32, 500_u32, 800_u32);
/// // Write the contents of this image in JPG format.
/// ```
#[wasm_bindgen]
pub fn crop(
    photon_image: &mut PhotonImage,
    x1: u32,
    y1: u32,
    x2: u32,
    y2: u32,
) -> PhotonImage {
    let img = helpers::dyn_image_from_raw(photon_image);

    let mut cropped_img: RgbaImage = ImageBuffer::new(x2 - x1, y2 - y1);

    for (x, y) in ImageIterator::with_dimension(&cropped_img.dimensions()) {
        let px = img.get_pixel(x1 + x, y1 + y);
        cropped_img.put_pixel(x, y, px);
    }
    let dynimage = ImageRgba8(cropped_img);
    let raw_pixels = dynimage.to_bytes();
    PhotonImage {
        raw_pixels,
        width: dynimage.width(),
        height: dynimage.height(),
    }
}

#[cfg(target_arch = "wasm32")]
#[wasm_bindgen]
pub fn crop_img_browser(
    source_canvas: HtmlCanvasElement,
    width: f64,
    height: f64,
    left: f64,
    top: f64,
) -> HtmlCanvasElement {
    let document = web_sys::window().unwrap().document().unwrap();
    let dest_canvas = document
        .create_element("canvas")
        .unwrap()
        .dyn_into::<web_sys::HtmlCanvasElement>()
        .unwrap();

    dest_canvas.set_width(width as u32);
    dest_canvas.set_height(height as u32);

    let ctx = dest_canvas
        .get_context("2d")
        .unwrap()
        .unwrap()
        .dyn_into::<web_sys::CanvasRenderingContext2d>()
        .unwrap();

    ctx.draw_image_with_html_canvas_element_and_sw_and_sh_and_dx_and_dy_and_dw_and_dh(
        &source_canvas,
        left,
        top,
        width,
        height,
        0.0,
        0.0,
        width,
        height,
    )
    .unwrap();

    dest_canvas
}

/// Flip an image horizontally.
///
/// # Arguments
/// * `img` - A PhotonImage.
///
/// # Example
///
/// ```no_run
/// // For example, to flip an image horizontally:
/// use photon_rs::native::open_image;
/// use photon_rs::transform::fliph;
///
/// let mut img = open_image("img.jpg").expect("File should open");
/// fliph(&mut img);
/// ```
#[wasm_bindgen]
pub fn fliph(photon_image: &mut PhotonImage) {
    let img = helpers::dyn_image_from_raw(photon_image);

    let width = img.width();
    let height = img.height();
    let mut flipped_img: RgbaImage = ImageBuffer::new(width, height);

    for (x, y) in ImageIterator::new(width, height) {
        let px = img.get_pixel(x, y);
        flipped_img.put_pixel(width - x - 1, y, px);
    }

    let dynimage = ImageRgba8(flipped_img);
    let raw_pixels = dynimage.to_bytes();
    photon_image.raw_pixels = raw_pixels;
}

/// Flip an image vertically.
///
/// # Arguments
/// * `img` - A PhotonImage.
///
/// # Example
///
/// ```no_run
/// // For example, to flip an image vertically:
/// use photon_rs::native::open_image;
/// use photon_rs::transform::flipv;
///
/// let mut img = open_image("img.jpg").expect("File should open");
/// flipv(&mut img);
/// ```
#[wasm_bindgen]
pub fn flipv(photon_image: &mut PhotonImage) {
    let img = helpers::dyn_image_from_raw(photon_image);

    let width = img.width();
    let height = img.height();

    let mut flipped_img: RgbaImage = ImageBuffer::new(width, height);

    for (x, y) in ImageIterator::new(width, height) {
        let px = img.get_pixel(x, y);
        flipped_img.put_pixel(x, height - y - 1, px);
    }

    let dynimage = ImageRgba8(flipped_img);
    let raw_pixels = dynimage.to_bytes();
    photon_image.raw_pixels = raw_pixels;
}

#[wasm_bindgen]
pub enum SamplingFilter {
    Nearest = 1,
    Triangle = 2,
    CatmullRom = 3,
    Gaussian = 4,
    Lanczos3 = 5,
}

fn filter_type_from_sampling_filter(sampling_filter: SamplingFilter) -> FilterType {
    match sampling_filter {
        SamplingFilter::Nearest => FilterType::Nearest,
        SamplingFilter::Triangle => FilterType::Triangle,
        SamplingFilter::CatmullRom => FilterType::CatmullRom,
        SamplingFilter::Gaussian => FilterType::Gaussian,
        SamplingFilter::Lanczos3 => FilterType::Lanczos3,
    }
}

/// Resize an image on the web.
///
/// # Arguments
/// * `img` - A PhotonImage.
/// * `width` - New width.
/// * `height` - New height.
/// * `sampling_filter` - Nearest = 1, Triangle = 2, CatmullRom = 3, Gaussian = 4, Lanczos3 = 5
#[cfg(target_arch = "wasm32")]
#[wasm_bindgen]
pub fn resize_img_browser(
    photon_img: &PhotonImage,
    width: u32,
    height: u32,
    sampling_filter: SamplingFilter,
) -> HtmlCanvasElement {
    let sampling_filter = filter_type_from_sampling_filter(sampling_filter);
    let dyn_img = helpers::dyn_image_from_raw(photon_img);
    let resized_img = ImageRgba8(image::imageops::resize(
        &dyn_img,
        width,
        height,
        sampling_filter,
    ));

    // TODO Check if in browser or Node.JS
    let document = web_sys::window().unwrap().document().unwrap();
    let canvas = document
        .create_element("canvas")
        .unwrap()
        .dyn_into::<web_sys::HtmlCanvasElement>()
        .unwrap();

    canvas.set_width(resized_img.width());
    canvas.set_height(resized_img.height());

    let new_img_data = ImageData::new_with_u8_clamped_array_and_sh(
        Clamped(&mut resized_img.to_bytes()),
        canvas.width(),
        canvas.height(),
    );

    let ctx = canvas
        .get_context("2d")
        .unwrap()
        .unwrap()
        .dyn_into::<web_sys::CanvasRenderingContext2d>()
        .unwrap();

    // Place the new imagedata onto the canvas
    ctx.put_image_data(&new_img_data.unwrap(), 0.0, 0.0)
        .unwrap();

    canvas
}

/// Resize an image.
///
/// # Arguments
/// * `img` - A PhotonImage.
/// * `width` - New width.
/// * `height` - New height.
/// * `sampling_filter` - Nearest = 1, Triangle = 2, CatmullRom = 3, Gaussian = 4, Lanczos3 = 5
#[wasm_bindgen]
pub fn resize(
    photon_img: &PhotonImage,
    width: u32,
    height: u32,
    sampling_filter: SamplingFilter,
) -> PhotonImage {
    let sampling_filter = filter_type_from_sampling_filter(sampling_filter);

    let dyn_img = helpers::dyn_image_from_raw(photon_img);
    let resized_img = ImageRgba8(image::imageops::resize(
        &dyn_img,
        width,
        height,
        sampling_filter,
    ));

    PhotonImage {
        raw_pixels: resized_img.to_bytes(),
        width: resized_img.width(),
        height: resized_img.height(),
    }
}

/// Resize image using seam carver.
/// Resize only if new dimensions are smaller, than original image.
/// # NOTE: This is still experimental feature, and pretty slow.
///
/// # Arguments
/// * `img` - A PhotonImage.
/// * `width` - New width.
/// * `height` - New height.
///
/// # Example
///
/// ```no_run
/// // For example, resize image using seam carver:
/// use photon_rs::native::open_image;
/// use photon_rs::transform::seam_carve;
/// use photon_rs::PhotonImage;
///
/// let img = open_image("img.jpg").expect("File should open");
/// let result: PhotonImage = seam_carve(&img, 100_u32, 100_u32);
/// ```
#[wasm_bindgen]
pub fn seam_carve(img: &PhotonImage, width: u32, height: u32) -> PhotonImage {
    let mut img: RgbaImage = ImageBuffer::from_raw(
        img.get_width(),
        img.get_height(),
        img.raw_pixels.to_vec(),
    )
    .unwrap();
    let (w, h) = img.dimensions();
    let (diff_w, diff_h) = (w - w.min(width), h - h.min(height));

    for _ in 0..diff_w {
        let vec_steam = imageproc::seam_carving::find_vertical_seam(&img);
        img = imageproc::seam_carving::remove_vertical_seam(&img, &vec_steam);
    }
    if diff_h.ne(&0_u32) {
        img = image::imageops::rotate90(&img);
        for _ in 0..diff_h {
            let vec_steam = imageproc::seam_carving::find_vertical_seam(&img);
            img = imageproc::seam_carving::remove_vertical_seam(&img, &vec_steam);
        }
        img = image::imageops::rotate270(&img);
    }

    let img = ImageRgba8(img);

    PhotonImage {
        raw_pixels: img.to_bytes(),
        width: img.width(),
        height: img.height(),
    }
}

/// Apply uniform padding around the PhotonImage
/// A padded PhotonImage is returned.
/// # Arguments
/// * `img` - A PhotonImage. See the PhotonImage struct for details.
/// * `padding` - The amount of padding to be applied to the PhotonImage.
/// * `padding_rgba` - Tuple containing the RGBA code for padding color.
///
/// # Example
///
/// ```no_run
/// // For example, to apply a padding of 10 pixels around a PhotonImage:
/// use photon_rs::transform::padding_uniform;
/// use photon_rs::native::open_image;
/// use photon_rs::Rgba;
///
/// let mut img = open_image("img.jpg").expect("File should open");
/// let rgba = Rgba::new(200_u8, 100_u8, 150_u8, 255_u8);
/// padding_uniform(&img, 10_u32, rgba);
/// ```
#[wasm_bindgen]
pub fn padding_uniform(
    img: &PhotonImage,
    padding: u32,
    padding_rgba: Rgba,
) -> PhotonImage {
    let image_buffer = img.get_raw_pixels();
    let img_width = img.get_width();
    let img_height = img.get_height();

    let mut img_padded_buffer = Vec::<u8>::new();
    let width_padded: u32 = img_width + 2 * padding;
    let height_padded: u32 = img_height + 2 * padding;

    for _ in 0..((width_padded + 1) * padding) {
        img_padded_buffer.push(padding_rgba.get_red());
        img_padded_buffer.push(padding_rgba.get_green());
        img_padded_buffer.push(padding_rgba.get_blue());
        img_padded_buffer.push(padding_rgba.get_alpha());
    }

    for i in (0..image_buffer.len()).step_by(4) {
        if (i / 4) % img_width as usize == 0 && i != 0 {
            for _ in (0..2 * padding).step_by(1) {
                img_padded_buffer.push(padding_rgba.get_red());
                img_padded_buffer.push(padding_rgba.get_green());
                img_padded_buffer.push(padding_rgba.get_blue());
                img_padded_buffer.push(padding_rgba.get_alpha());
            }
        }
        img_padded_buffer.push(image_buffer[i]);
        img_padded_buffer.push(image_buffer[i + 1]);
        img_padded_buffer.push(image_buffer[i + 2]);
        img_padded_buffer.push(image_buffer[i + 3]);
    }

    for _ in 0..((width_padded + 1) * padding) {
        img_padded_buffer.push(padding_rgba.get_red());
        img_padded_buffer.push(padding_rgba.get_green());
        img_padded_buffer.push(padding_rgba.get_blue());
        img_padded_buffer.push(padding_rgba.get_alpha());
    }

    PhotonImage::new(img_padded_buffer, width_padded, height_padded)
}

/// Apply padding on the left side of the PhotonImage
/// A padded PhotonImage is returned.
/// # Arguments
/// * `img` - A PhotonImage. See the PhotonImage struct for details.
/// * `padding` - The amount of padding to be applied to the PhotonImage.
/// * `padding_rgba` - Tuple containing the RGBA code for padding color.
///
/// # Example
///
/// ```no_run
/// // For example, to apply a padding of 10 pixels on the left side of a PhotonImage:
/// use photon_rs::transform::padding_left;
/// use photon_rs::native::open_image;
/// use photon_rs::Rgba;
///
/// let mut img = open_image("img.jpg").expect("File should open");
/// let rgba = Rgba::new(200_u8, 100_u8, 150_u8, 255_u8);
/// padding_left(&img, 10_u32, rgba);
/// ```
#[wasm_bindgen]
pub fn padding_left(img: &PhotonImage, padding: u32, padding_rgba: Rgba) -> PhotonImage {
    let image_buffer = img.get_raw_pixels();
    let img_width = img.get_width();
    let img_height = img.get_height();

    let mut img_padded_buffer = Vec::<u8>::new();
    let width_padded: u32 = img_width + padding;

    for i in 0..img_height as usize {
        let img_slice = image_buffer
            [(i * 4 * img_width as usize)..(i + 1) * 4 * img_width as usize]
            .to_owned();

        for _ in 0..padding {
            img_padded_buffer.push(padding_rgba.get_red());
            img_padded_buffer.push(padding_rgba.get_green());
            img_padded_buffer.push(padding_rgba.get_blue());
            img_padded_buffer.push(padding_rgba.get_alpha());
        }
        for x in img_slice {
            img_padded_buffer.push(x);
        }
    }
    PhotonImage::new(img_padded_buffer, width_padded, img_height)
}

/// Apply padding on the left side of the PhotonImage
/// A padded PhotonImage is returned.
/// # Arguments
/// * `img` - A PhotonImage. See the PhotonImage struct for details.
/// * `padding` - The amount of padding to be applied to the PhotonImage.
/// * `padding_rgba` - Tuple containing the RGBA code for padding color.
///
/// # Example
///
/// ```no_run
/// // For example, to apply a padding of 10 pixels on the right side of a PhotonImage:
/// use photon_rs::transform::padding_right;
/// use photon_rs::native::open_image;
/// use photon_rs::Rgba;
///
/// let mut img = open_image("img.jpg").expect("File should open");
/// let rgba = Rgba::new(200_u8, 100_u8, 150_u8, 255_u8);
/// padding_right(&img, 10_u32, rgba);
/// ```
#[wasm_bindgen]
pub fn padding_right(
    img: &PhotonImage,
    padding: u32,
    padding_rgba: Rgba,
) -> PhotonImage {
    let image_buffer = img.get_raw_pixels();
    let img_width = img.get_width();
    let img_height = img.get_height();

    let mut img_padded_buffer = Vec::<u8>::new();
    let width_padded: u32 = img_width + padding;

    for i in 0..img_height as usize {
        let img_slice = image_buffer
            [(i * 4 * img_width as usize)..(i + 1) * 4 * img_width as usize]
            .to_owned();
        for x in img_slice {
            img_padded_buffer.push(x);
        }
        for _ in 0..padding {
            img_padded_buffer.push(padding_rgba.get_red());
            img_padded_buffer.push(padding_rgba.get_green());
            img_padded_buffer.push(padding_rgba.get_blue());
            img_padded_buffer.push(padding_rgba.get_alpha());
        }
    }
    PhotonImage::new(img_padded_buffer, width_padded, img_height)
}

/// Apply padding on the left side of the PhotonImage
/// A padded PhotonImage is returned.
/// # Arguments
/// * `img` - A PhotonImage. See the PhotonImage struct for details.
/// * `padding` - The amount of padding to be applied to the PhotonImage.
/// * `padding_rgba` - Tuple containing the RGBA code for padding color.
///
/// # Example
///
/// ```no_run
/// // For example, to apply a padding of 10 pixels on the top of a PhotonImage:
/// use photon_rs::transform::padding_top;
/// use photon_rs::native::open_image;
/// use photon_rs::Rgba;
///
/// let mut img = open_image("img.jpg").expect("File should open");
/// let rgba = Rgba::new(200_u8, 100_u8, 150_u8, 255_u8);
/// padding_top(&img, 10_u32, rgba);
/// ```
#[wasm_bindgen]
pub fn padding_top(img: &PhotonImage, padding: u32, padding_rgba: Rgba) -> PhotonImage {
    let image_buffer = img.get_raw_pixels();
    let img_width = img.get_width();
    let img_height = img.get_height();

    let height_padded: u32 = img_height + padding;
    let mut img_padded_buffer: Vec<u8> = Vec::<u8>::new();

    for _ in 0..(padding * img_width) {
        img_padded_buffer.push(padding_rgba.get_red());
        img_padded_buffer.push(padding_rgba.get_green());
        img_padded_buffer.push(padding_rgba.get_blue());
        img_padded_buffer.push(padding_rgba.get_alpha());
    }

    for i in (0..image_buffer.len()).step_by(4) {
        img_padded_buffer.push(image_buffer[i]);
        img_padded_buffer.push(image_buffer[i + 1]);
        img_padded_buffer.push(image_buffer[i + 2]);
        img_padded_buffer.push(image_buffer[i + 3]);
    }

    PhotonImage::new(img_padded_buffer, img_width, height_padded)
}

/// Apply padding on the left side of the PhotonImage
/// A padded PhotonImage is returned.
/// # Arguments
/// * `img` - A PhotonImage. See the PhotonImage struct for details.
/// * `padding` - The amount of padding to be applied to the PhotonImage.
/// * `padding_rgba` - Tuple containing the RGBA code for padding color.
///
/// # Example
///
/// ```no_run
/// // For example, to apply a padding of 10 pixels on the bottom of a PhotonImage:
/// use photon_rs::transform::padding_bottom;
/// use photon_rs::native::open_image;
/// use photon_rs::Rgba;
///
/// let mut img = open_image("img.jpg").expect("File should open");
/// let rgba = Rgba::new(200_u8, 100_u8, 150_u8, 255_u8);
/// padding_bottom(&img, 10_u32, rgba);
/// ```
#[wasm_bindgen]
pub fn padding_bottom(
    img: &PhotonImage,
    padding: u32,
    padding_rgba: Rgba,
) -> PhotonImage {
    let image_buffer = img.get_raw_pixels();
    let img_width = img.get_width();
    let img_height = img.get_height();

    let height_padded: u32 = img_height + padding;
    let mut img_padded_buffer: Vec<u8> = Vec::<u8>::new();

    for i in (0..image_buffer.len()).step_by(4) {
        img_padded_buffer.push(image_buffer[i]);
        img_padded_buffer.push(image_buffer[i + 1]);
        img_padded_buffer.push(image_buffer[i + 2]);
        img_padded_buffer.push(image_buffer[i + 3]);
    }

    for _ in 0..(padding * img_width) {
        img_padded_buffer.push(padding_rgba.get_red());
        img_padded_buffer.push(padding_rgba.get_green());
        img_padded_buffer.push(padding_rgba.get_blue());
        img_padded_buffer.push(padding_rgba.get_alpha());
    }

    PhotonImage::new(img_padded_buffer, img_width, height_padded)
}

/// Rotate the PhotonImage on an arbitrary angle
/// A rotated PhotonImage is returned.
/// # NOTE: This is a naive implementation. Paeth rotation should be faster.
///
/// # Arguments
/// * `img` - A PhotonImage. See the PhotonImage struct for details.
/// * `angle` - Rotation angle in degrees.
///
/// # Example
///
/// ```no_run
/// // For example, to rotate a PhotonImage by 30 degrees:
/// use photon_rs::native::open_image;
/// use photon_rs::transform::rotate;
///
/// let img = open_image("img.jpg").expect("File should open");
/// let rotated_img = rotate(&img, 30);
/// ```
#[wasm_bindgen]
pub fn rotate(img: &PhotonImage, angle: i32) -> PhotonImage {
    // 390, 750 and 30 degrees represent the same angle. Trim 360.
    let full_circle_count = angle / 360;
    let normalized_angle = angle - full_circle_count * 360;
    if normalized_angle == 0 {
        return img.clone();
    }

    // Handle negative angles. -80 describes the same angle as 360 - 80 = 280.
    let positive_angle = if normalized_angle < 0 {
        normalized_angle + 360
    } else {
        normalized_angle
    };

    // Count the number of rotations by right angle and apply them via rotate90 if necessary.
    let right_angle_count = positive_angle / 90;
    let mut rgba_img: RgbaImage = ImageBuffer::from_raw(
        img.get_width(),
        img.get_height(),
        img.raw_pixels.to_vec(),
    )
    .unwrap();
    for _ in 0..right_angle_count {
        rgba_img = image::imageops::rotate90(&rgba_img);
    }

    let dynimage = ImageRgba8(rgba_img);
    let raw_pixels = dynimage.to_bytes();
    let src_width = dynimage.width();
    let src_height = dynimage.height();

    let angle_deg = positive_angle - right_angle_count * 90;
    if angle_deg == 0 {
        return PhotonImage {
            raw_pixels,
            width: src_width,
            height: src_height,
        };
    }

    // Convert degrees to radians and calculate sine and cosine parts.
    let angle_rad = angle_deg as f64 * std::f64::consts::PI / 180.0;
    let cosine = angle_rad.cos();
    let sine = angle_rad.sin();

    // Move (0, 0) point to (w / 2, h / 2) in order to rotate around the centre.
    let src_centre_x = src_width / 2;
    let src_centre_y = src_height / 2;
    let src_centre_x_f64 = src_centre_x as f64;
    let src_centre_y_f64 = src_centre_y as f64;

    // (-cx, cy) corner will contain the leftmost x after the rotation.
    let leftmost_pos = -1.0 * src_centre_x_f64 * cosine - src_centre_y_f64 * sine;
    let leftmost_pos = leftmost_pos.floor() as i32;

    // (cx, -cy) corner will contain the rightmost x after the rotation.
    let rightmost_pos = src_centre_x_f64 * cosine + src_centre_y_f64 * sine;
    let rightmost_pos = rightmost_pos.floor() as i32;

    // (-cx, -cy) corner will contain the least y after the rotation.
    let bottom_pos = -1.0 * src_centre_x_f64 * sine - src_centre_y_f64 * cosine;
    let bottom_pos = bottom_pos.floor() as i32;

    // (cx, cy) corner will contain the largest y after the rotation.
    let top_pos = src_centre_x_f64 * sine + src_centre_y_f64 * cosine;
    let top_pos = top_pos.floor() as i32;

    // Move (0, 0) point to (w / 2, h / 2) target image as well.
    let dst_width = rightmost_pos - leftmost_pos;
    let dst_width = dst_width as u32;
    let dst_height = top_pos - bottom_pos;
    let dst_height = dst_height as u32;
    let dst_centre_x = dst_width / 2;
    let dst_centre_y = dst_height / 2;

    // Allocate destination buffer.
    let channel_count = 4;
    let mut result = Vec::<u8>::new();
    let total_dst_size = (dst_width * dst_height * channel_count)
        .try_into()
        .expect("Failed to calculate destination size");
    result.resize(total_dst_size, 0);

    // Calculate source and target strides.
    let stride_chan = 1;
    let src_stride_col = channel_count * stride_chan;
    let src_stride_row = src_width * src_stride_col;
    let dst_stride_col = channel_count * stride_chan;
    let dst_stride_row = dst_width * dst_stride_col;

    for row in 0..src_height {
        for col in 0..src_width {
            // Rows and columns are counted from 0 to width and height.
            // In order to get coordinates relative to (w / 2, h / 2) subtract centre point.
            let src_x = (col as i32 - src_centre_x as i32) as f64;
            let src_y = (row as i32 - src_centre_y as i32) as f64;

            // Rotation.
            let dst_x = src_x * cosine - src_y * sine + dst_centre_x as f64;
            let dst_x = dst_x.floor() as u32;
            let dst_x = max(0, dst_x);
            let dst_x = min(dst_width - 1, dst_x);

            let dst_y = src_x * sine + src_y * cosine + dst_centre_y as f64;
            let dst_y = dst_y.floor() as u32;
            let dst_y = max(0, dst_y);
            let dst_y = min(dst_height - 1, dst_y);

            // Translate coordinates to the buffer offsets.
            let src_idx = (row * src_stride_row + col * src_stride_col) as usize;
            let dst_idx = (dst_y * dst_stride_row + dst_x * dst_stride_col) as usize;

            for chan in 0..channel_count {
                let chan = chan as usize;
                result[dst_idx + chan] = raw_pixels[src_idx + chan];

                // FIXME apply proper interpolation
                result[dst_idx + 4 + chan] = raw_pixels[src_idx + chan];
            }
        }
    }

    PhotonImage::new(result, dst_width, dst_height)
}

fn greatest_common_divisor(left_val: usize, right_val: usize) -> usize {
    let mut a = left_val;
    let mut b = right_val;
    while b > 0 {
        let t = b;
        b = a % b;
        a = t;
    }
    a
}

fn copy_row(buf: &[u8], row_pos: usize, row_stride: usize) -> Vec<u8> {
    let mut result = Vec::<u8>::new();
    for byte_idx in 0..row_stride {
        let src_idx = (row_pos * row_stride) + byte_idx;
        result.push(buf[src_idx]);
    }

    result
}

/// Resample the PhotonImage.
///
/// # Arguments
/// * `img` - A PhotonImage. See the PhotonImage struct for details.
/// * `dst_width` - Target width.
/// * `dst_height` - Target height.
///
/// # Example
///
/// ```no_run
/// // For example, to resample a PhotonImage to 1920x1080 size:
/// use photon_rs::native::open_image;
/// use photon_rs::transform::resample;
///
/// let img = open_image("img.jpg").expect("File should open");
/// let rotated_img = resample(&img, 1920, 1080);
/// ```
#[wasm_bindgen]
pub fn resample(img: &PhotonImage, dst_width: usize, dst_height: usize) -> PhotonImage {
    let mut pix_buf = Vec::<u8>::new();
    if dst_width == 0 || dst_height == 0 {
        return PhotonImage::new(pix_buf, dst_width as u32, dst_height as u32);
    }

    let src_width = img.get_width() as usize;
    let src_height = img.get_height() as usize;

    // The idea is to upsample source width to the greatest commond divisor, then downsample to
    // target width. For example: resample 240 to 320. The greatest common divisor is 80.
    // At first, upsample 240 to 960 (960 is 240 * 320 / 80)
    // Next downsample 960 to 320 (320 is 960 / (240 / 80)).
    // Thus, upsampling rate is 320 / 80 = 4, downsampling rate is 240 / 80 = 3.
    let width_gcd = greatest_common_divisor(src_width, dst_width);
    let height_gcd = greatest_common_divisor(src_height, dst_height);
    let upsample_x = dst_width / width_gcd;
    let downsample_x = src_width / width_gcd;
    let upsample_y = dst_height / height_gcd;
    let downsample_y = src_height / height_gcd;

    // Upsampling and downsampling are performed in the same loop.
    // Upsample the image while the size is indivisible by downsampling rate.
    // Then downsample and clear the buffer.
    // For example, upsampling rate is 3 and downsampling rate is 4.
    // After processing 4 pixels, buffer gets 12 pixels (repeats each pixel 3 times).
    // 12 pixels can be downsampled by 4, so downsampling takes every 4th pixel.
    // The result contains 3 pixels. That approach is somewhat slower but requires less memory.
    let img_pixels = &img.raw_pixels;
    let src_chan = 4;

    // Resample width.
    let mut resampled_width = Vec::<u8>::new();
    for row in 0..src_height {
        // Upsample pixels and put them to temporary buffer.
        let mut upsampled_width = Vec::<u8>::new();
        for col in 0..src_width {
            for _i in 0..upsample_x {
                for chan in 0..src_chan {
                    let src_idx = (row * src_width * src_chan) + col * src_chan + chan;
                    upsampled_width.push(img_pixels[src_idx]);
                }
            }

            // When the temporary buffer can be downsampled, downsample and clear it.
            let upsampled_pix_count = upsampled_width.len() / src_chan;
            if (upsampled_pix_count % downsample_x) == 0 {
                for i in 0..upsampled_pix_count / downsample_x {
                    for chan in 0..src_chan {
                        let src_idx = (i * downsample_x) * src_chan + chan;
                        resampled_width.push(upsampled_width[src_idx]);
                    }
                }
                upsampled_width.clear();
            }
        }
    }

    // Resample height.
    let mut upsampled_height = Vec::<u8>::new();
    for row in 0..src_height {
        // Upsample rows and put them to temporary buffer.
        for _i in 0..upsample_y {
            let mut row_copy = copy_row(&resampled_width, row, dst_width * src_chan);
            upsampled_height.append(&mut row_copy);
        }

        // When the temporary buffer can be downsampled, downsample and clear it.
        let upsampled_rows_count = upsampled_height.len() / src_chan / dst_width;
        if (upsampled_rows_count % downsample_y) == 0 {
            for i in 0..upsampled_rows_count / downsample_y {
                let mut row_copy =
                    copy_row(&upsampled_height, i * downsample_y, dst_width * src_chan);
                pix_buf.append(&mut row_copy);
            }
            upsampled_height.clear();
        }
    }

    PhotonImage::new(pix_buf, dst_width as u32, dst_height as u32)
}

/// Compression
///
/// # Arguments
/// * `img` - A PhotonImage.
/// * `quality` - The Quality of the returned PhotonImage.
///
/// # Example
///
/// ```no_run
/// use photon_rs::native::open_image;
/// use photon_rs::transform::compress;
///
/// let image = open_image("img.jpg").expect("File should open");
///
/// let compressed_image = compress(&image, 50);
/// ```
/// Adds a constant to a select R, G, or B channel's value.
pub fn compress(img: &PhotonImage, quality: u8) -> PhotonImage {
    let bytes = img.get_bytes_jpeg(quality);

    PhotonImage::new_from_byteslice(bytes)
}