首先把当前页面转换成bitmap
<strong> </strong> View view = viewRl.getRootView();
view.setDrawingCacheEnabled(true);
Bitmap bitmap = view.getDrawingCache();
viewRl为布局的根id
this.viewRl= (RelativeLayout) findViewById(R.id.viewRl);
然后把bitmap缓存到sd中
public static String saveCroppedImageSD(Bitmap bmp,Context context) {
//获取应用包名
PackageManager pm = context.getPackageManager();
String appName = context.getApplicationInfo().loadLabel(pm).toString();
String sdPath= Environment.getExternalStorageDirectory().getPath();
File file = new File(sdPath+"/"+appName);
if (!file.exists())
file.mkdir();
// /sdcard/包名/temp_cropped.jpg
String newFilePath = sdPath+"/"+appName + "/" + "temp_cropped.jpg" ;
file = new File(newFilePath);
try {
file.createNewFile();
FileOutputStream fos = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 50, fos);
fos.flush();
fos.close();
if(file.exists()){
Log.v("保存bitmap为缓存文件111", "成功保存bitmap:"+file.getPath());
}
return newFilePath;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
当然也可以进行图片的删除
public static void deleteCacheImage(Context context){
//获取应用包名
PackageManager pm = context.getPackageManager();
String appName = context.getApplicationInfo().loadLabel(pm).toString();
String sdPath= Environment.getExternalStorageDirectory().getPath();
File file = new File(sdPath+"/"+appName+"/temp_cropped.jpg");
if(file.exists()){
file.delete();
}
}<pre name="code" class="html">
除了可以保存到sd中,也可以创建缓存,放在缓存中
public static String saveCroppedImageCache(Bitmap bmp, Context context) {
try {
//获取缓存地址
File outputDir = context.getCacheDir();
//创建缓存文件
File outputFile = File.createTempFile(System.currentTimeMillis() + "", ".jpg", outputDir);
FileOutputStream fos = new FileOutputStream(outputFile);
bmp.compress(Bitmap.CompressFormat.JPEG, 50, fos);
fos.flush();
fos.close();
//保存位置
// String imgUrl= context.getCacheDir()+"/"+ outputFile.getName();
if(outputFile.exists()){
Log.e("保存bitmap为缓存文件111", "成功保存bitmap:"+outputFile.getPath());
}
return outputFile.getPath();
} catch (IOException e) {
e.printStackTrace();
Log.e("保存bitmap为缓存文件", "失败保存bitmap");
}
return null;
}