android两个drawable资源,android – 如何将一个Drawable资源写入文件?

虽然这里最好的答案有一个很好的方法.它只是链接.以下是如何执行以下步骤:

将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,使你的应用程序无响应.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值