11use std:: io:: Cursor ;
22
3- use image :: imageops :: FilterType ;
3+ use fast_image_resize :: { CropBox , FilterType , ResizeAlg , ResizeOptions , Resizer , SrcCropping } ;
44use image:: { DynamicImage , ImageFormat , ImageReader } ;
55
66use crate :: error:: Error ;
@@ -9,8 +9,8 @@ use crate::Result;
99pub struct Image {
1010 format : ImageFormat ,
1111 image_src : DynamicImage ,
12- width : usize ,
13- height : usize ,
12+ width : u32 ,
13+ height : u32 ,
1414}
1515
1616impl TryFrom < Vec < u8 > > for Image {
@@ -23,8 +23,8 @@ impl TryFrom<Vec<u8>> for Image {
2323 . ok_or ( Error :: Parse ( "image format could not be guessed." . into ( ) ) ) ?;
2424
2525 let image_src = reader. decode ( ) ?;
26- let width = image_src. width ( ) as usize ;
27- let height = image_src. height ( ) as usize ;
26+ let width = image_src. width ( ) ;
27+ let height = image_src. height ( ) ;
2828
2929 Ok ( Image {
3030 format,
@@ -51,13 +51,29 @@ impl Image {
5151 self . format
5252 }
5353
54- pub fn resize ( mut self , width : usize , height : usize ) -> Result < Self > {
55- self . image_src =
56- self . image_src
57- . resize_to_fill ( width as u32 , height as u32 , FilterType :: Triangle ) ;
58- self . width = width;
59- self . height = height;
54+ pub fn resize ( self , width : u32 , height : u32 ) -> Result < Self > {
55+ let mut image_src = DynamicImage :: new ( width, height, self . image_src . color ( ) ) ;
6056
61- Ok ( self )
57+ let mut resizer = Resizer :: new ( ) ;
58+ let resize_options = ResizeOptions {
59+ algorithm : ResizeAlg :: Convolution ( FilterType :: Lanczos3 ) ,
60+ cropping : SrcCropping :: Crop ( CropBox :: fit_src_into_dst_size (
61+ self . width ,
62+ self . height ,
63+ width,
64+ height,
65+ Some ( ( 0.5 , 0.5 ) ) ,
66+ ) ) ,
67+ ..Default :: default ( )
68+ } ;
69+
70+ resizer. resize ( & self . image_src , & mut image_src, Some ( & resize_options) ) ?;
71+
72+ Ok ( Image {
73+ format : self . format ,
74+ image_src,
75+ width,
76+ height,
77+ } )
6278 }
6379}
0 commit comments