1 将本地图片地址转成Bitmap
public static Bitmap pathToBitmap ( String path) {
return BitmapFactory. decodeFile ( path) ;
}
2.将Bitmap转成File(可以把文件传递到后台)
public static File saveImage ( String filePath, Bitmap bitmap, long size) {
File result = new File ( filePath. substring ( 0 , filePath. lastIndexOf ( "/" ) ) ) ;
if ( ! result. exists ( ) && ! result. mkdirs ( ) ) return null;
ByteArrayOutputStream stream = new ByteArrayOutputStream ( ) ;
int options = 100 ;
bitmap. compress ( Bitmap. CompressFormat. JPEG, options, stream) ;
while ( stream. toByteArray ( ) . length / 1024 > size && options > 6 ) {
stream. reset ( ) ;
options -= 6 ;
bitmap. compress ( Bitmap. CompressFormat. JPEG, options, stream) ;
}
try {
FileOutputStream fos = new FileOutputStream ( filePath) ;
fos. write ( stream. toByteArray ( ) ) ;
fos. flush ( ) ;
fos. close ( ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
return new File ( filePath) ;
}
2.1使用方法:
SimpleDateFormat format = new SimpleDateFormat ( "yyyyMMddHHmmss" ) ;
Date date = new Date ( System. currentTimeMillis ( ) ) ;
String filename = format. format ( date) ;
File file = new File ( Environment. getExternalStorageDirectory ( ) , filename + ".png" ) ;
saveImage ( file. getAbsolutePath ( ) , bitmap, 20 ) ;
3 将bitmap转成本地图片
public static void saveImage ( String path, Bitmap bitmap) {
try {
BufferedOutputStream bos = new BufferedOutputStream ( new FileOutputStream ( path) ) ;
bitmap. compress ( Bitmap. CompressFormat. JPEG, 80 , bos) ;
bos. flush ( ) ;
bos. close ( ) ;
} catch ( FileNotFoundException e) {
e. printStackTrace ( ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
}
3.1 使用方法:
SimpleDateFormat format = new SimpleDateFormat ( "yyyyMMddHHmmss" ) ;
Date date = new Date ( System. currentTimeMillis ( ) ) ;
String filename = format. format ( date) ;
File file = new File ( Environment. getExternalStorageDirectory ( ) , filename + ".png" ) ;
saveImage ( file. getAbsolutePath ( ) , bitmap)