public String compress ( int drawableID ) throws IOException { // Create a bitmap from this drawable Bitmap bitmap = BitmapFactory . decodeResource ( mContext . getApplicationContext ( ) . getResources ( ) , drawableID ) ; if ( null != bitmap ) { // Create a file from the bitmap // Create an image file name String timeStamp = new SimpleDateFormat ( "yyyyMMdd_HHmmss" , Locale . ENGLISH ) . format ( new Date ( ) ) ; String imageFileName = "JPEG_" + timeStamp + "_" ; File storageDir = Environment . getExternalStoragePublicDirectory ( Environment . DIRECTORY_PICTURES ) ; File image = File . createTempFile ( imageFileName , /* prefix */ ".jpg" , /* suffix */ storageDir /* directory */ ) ; FileOutputStream out = new FileOutputStream ( image ) ; bitmap . compress ( Bitmap . CompressFormat . JPEG , 100 , out ) ; // Compress the new file Uri copyImageUri = FileProvider . getUriForFile ( mContext , FILE_PROVIDER_AUTHORITY , image ) ; String compressedImagePath = compressImage ( image . getAbsolutePath ( ) , new File ( Environment . getExternalStoragePublicDirectory ( Environment . DIRECTORY_PICTURES ) , "Silicompressor/images" ) ) ; // Delete the file created from the drawable Id if ( image . exists ( ) ) { deleteImageFile ( image . getAbsolutePath ( ) ) ; } // return the path to the compressed image return compressedImagePath ; } return null ; }
Compress drawable file with specified drawableID