File tree Expand file tree Collapse file tree 1 file changed +29
-1
lines changed Expand file tree Collapse file tree 1 file changed +29
-1
lines changed Original file line number Diff line number Diff line change @@ -136,7 +136,35 @@ impl Source {
136136 let img_buffer = ImageBuffer :: from_raw ( size, size, pixmap. take ( ) ) . unwrap ( ) ;
137137 Ok ( DynamicImage :: ImageRgba8 ( img_buffer) )
138138 }
139- Self :: DynamicImage ( i) => Ok ( i. resize_exact ( size, size, FilterType :: Lanczos3 ) ) ,
139+ Self :: DynamicImage ( i) => {
140+ // Step 1: Premultiply alpha
141+ let mut buf = i. to_rgba8 ( ) ;
142+ for pixel in buf. pixels_mut ( ) {
143+ let a = pixel[ 3 ] as u32 ;
144+ pixel[ 0 ] = ( ( pixel[ 0 ] as u32 * a + 127 ) / 255 ) as u8 ;
145+ pixel[ 1 ] = ( ( pixel[ 1 ] as u32 * a + 127 ) / 255 ) as u8 ;
146+ pixel[ 2 ] = ( ( pixel[ 2 ] as u32 * a + 127 ) / 255 ) as u8 ;
147+ }
148+ let premultiplied = DynamicImage :: ImageRgba8 ( buf) ;
149+
150+ // Step 2: Resize
151+ let mut resized = premultiplied. resize_exact ( size, size, FilterType :: Lanczos3 ) . to_rgba8 ( ) ;
152+
153+ // Step 3: Unpremultiply alpha and zero RGB for fully transparent
154+ for pixel in resized. pixels_mut ( ) {
155+ let a = pixel[ 3 ] as u32 ;
156+ if a == 0 {
157+ pixel[ 0 ] = 0 ;
158+ pixel[ 1 ] = 0 ;
159+ pixel[ 2 ] = 0 ;
160+ } else {
161+ pixel[ 0 ] = ( ( pixel[ 0 ] as u32 * 255 + a / 2 ) / a) . min ( 255 ) as u8 ;
162+ pixel[ 1 ] = ( ( pixel[ 1 ] as u32 * 255 + a / 2 ) / a) . min ( 255 ) as u8 ;
163+ pixel[ 2 ] = ( ( pixel[ 2 ] as u32 * 255 + a / 2 ) / a) . min ( 255 ) as u8 ;
164+ }
165+ }
166+ Ok ( DynamicImage :: ImageRgba8 ( resized) )
167+ }
140168 }
141169 }
142170}
You can’t perform that action at this time.
0 commit comments