虽然这里最好的答案有一个很好的方法.它只是链接.以下是如何执行以下步骤:
将Drawable转换为位图
您可以使用至少两种不同的方法,这取决于您从哪里获取Drawable.
> Drawable是在res / drawable文件夹.
假设您要使用可绘制的文件夹上的Drawable.您可以使用BitmapFactory#decodeResource方法.下面的例子.
Bitmap bm = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.your_drawable);
如果您在“运行时”从其他地方获得PictureDrawable,则可以使用Bitmap#createBitmap方法创建位图.像下面的例子.
public Bitmap drawableToBitmap(PictureDrawable pd) {
Bitmap bm = Bitmap.createBitmap(pd.getIntrinsicWidth(), pd.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bm);
canvas.drawPicture(pd.getPicture());
return bm;
}
将位图保存到磁盘
一旦你有了Bitmap对象,你可以把它保存到永久存储.您只需要选择文件格式(JPEG,PNG或WEBP).
/*
* Bitmap.CompressFormat can be PNG,JPEG or WEBP.
*
* quality goes from 1 to 100. (Percentage).
*
* dir you can get from many places like Environment.getExternalStorageDirectory() or mContext.getFilesDir()
* depending on where you want to save the image.
*/
public boolean saveBitmapToFile(File dir, String fileName, Bitmap bm,
Bitmap.CompressFormat format, int quality) {
File imageFile = new File(dir,fileName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(imageFile);
bm.compress(format,quality,fos);
fos.close();
return true;
}
catch (IOException e) {
Log.e("app",e.getMessage());
if (fos != null) {
try {
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
return false;
}
要获取目标目录,请尝试以下操作:
File dir = new File(Environment.getExternalStorageDirectory() + File.separator + "drawable");
boolean doSave = true;
if (!dir.exists()) {
doSave = dir.mkdirs();
}
if (doSave) {
saveBitmapToFile(dir,"theNameYouWant.png",bm,Bitmap.CompressFormat.PNG,100);
}
else {
Log.e("app","Couldn't create target directory.");
}
Obs:记住在背景线上做这样的工作如果你正在处理大图像或许多图像,因为它可能需要一些时间才能完成,并可能会阻止你的UI,使你的应用程序无响应.