public Bitmap getScaledBitmap ( Bitmap bitmap , int scaleToWidth , int scaleToHeight , boolean recycleOriginal , int density ) { bitmap . setDensity ( density ) ; Bitmap original = bitmap ; if ( scaleToWidth > 0 || scaleToHeight > 0 ) { int width = bitmap . getWidth ( ) ; int height = bitmap . getHeight ( ) ; // scale lowest and crop highes if ( height != scaleToHeight || width != scaleToWidth ) { float ratio = 1.0f ; // Scale to smallest if ( height > width ) { ratio = ( float ) scaleToWidth / ( float ) width ; width = scaleToWidth ; height = Math . round ( ( float ) height * ratio ) ; bitmap = bitmapBuilder . scale ( bitmap , width , height ) ; width = bitmap . getWidth ( ) ; height = bitmap . getHeight ( ) ; if ( height > scaleToHeight ) { // crop height int diff = height - scaleToHeight ; int half = Math . round ( ( float ) diff / 2.0f ) ; bitmap = bitmapBuilder . crop ( bitmap , 0 , half , width , scaleToHeight ) ; } } else { ratio = ( float ) scaleToHeight / ( float ) height ; height = scaleToHeight ; width = Math . round ( ( float ) width * ratio ) ; bitmap = bitmapBuilder . scale ( bitmap , width , height ) ; width = bitmap . getWidth ( ) ; height = bitmap . getHeight ( ) ; if ( width > scaleToWidth ) { // crop width int diff = width - scaleToWidth ; int half = Math . round ( ( float ) diff / 2.0f ) ; bitmap = bitmapBuilder . crop ( bitmap , half , 0 , scaleToWidth , height ) ; } } if ( recycleOriginal ) { original . recycle ( ) ; } } } return bitmap ; }
Returns a scaled bitmap cropped if necessary .