将Bitmap存储到本地:
public void SaveImage(Bitmap image, String user_id){
//照片通常存在DCIM文件夹中
String sdCardDir = getApplicationContext().getCacheDir()+"/DCIM/";
// String sdCardDir = Environment.getExternalStorageDirectory()+"/DCIM/";
//为APP创建一个文件夹来存储图片
File appDir = new File(sdCardDir, "MyGraduation");
if(!appDir.exists()){
appDir.mkdirs();
}
//图片名称
String fileName = user_id+".jpg";
//设置图片路径
File imageDir = new File(appDir, fileName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(imageDir);
image.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
System.out.println(imageDir.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
从本地读取到Bitmap文件:
public Bitmap getImage(String user_id){
String sdCardDir = getApplicationContext().getCacheDir()+"/DCIM/";
// String sdCardDir = Environment.getExternalStorageDirectory()+"/DCIM/";
String path = sdCardDir+"MyGraduation/"+user_id+".jpg";
Bitmap bitmap = null;
FileInputStream fis = null;
File f=new File(path);
if(!f.exists())
{
return null;
}
try {
fis = new FileInputStream(path);
bitmap = BitmapFactory.decodeStream(fis);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return bitmap;
}
读取和改写SD卡需要权限:
<uses-permission android:name="android.permission.WRITE_SETTINGS" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_OWNER_DATA" />
从imageView中获取bitmap:
Bitmap bitmap = ((BitmapDrawable)iv_user_head.getDrawable()).getBitmap();