我需要将一些 Drawable
资源导出到文件中。
例如,我有一个函数返回一个 Drawable
对象。 我想将它写入到 /sdcard/drawable/newfile.png
文件中。如何实现?
虽然这里的最佳答案有一个不错的方法,但它只是链接。以下是你可以执行的步骤:
您可以以至少两种不同的方式来完成此操作,具体取决于您从何处获取Drawable
。
res/drawable
文件夹中。假设您想要使用位于drawable文件夹中的Drawable
。您可以使用BitmapFactory#decodeResource
方法。以下是示例。
Bitmap bm = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.your_drawable);
PictureDrawable
对象。如果你从其他地方“在运行时”获取了PictureDrawable
,你可以使用Bitmap#createBitmap
方法来创建你的Bitmap
。就像下面的例子一样。
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)。
/**
* @param dir you can get from many places like Environment.getExternalStorageDirectory() or mContext.getFilesDir() depending on where you want to save the image.
* @param fileName The file name.
* @param bm The Bitmap you want to save.
* @param format Bitmap.CompressFormat can be PNG,JPEG or WEBP.
* @param quality quality goes from 1 to 100. (Percentage).
* @return true if the Bitmap was saved successfully, false otherwise.
*/
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.");
}
注意:如果您处理大型图像或多个图像,请在后台线程上执行此类工作,因为完成可能需要一些时间,并可能阻止您的用户界面,使您的应用程序无响应。
获取存储在SD卡中的图像..
File imgFile = new File(“/sdcard/Images/test_image.jpg”);
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);
myImage.setImageBitmap(myBitmap);
}
String path = Environment.getExternalStorageDirectory()+ "/Images/test.jpg";
File imgFile = new File(path);
Environment.getExternalStorageDirectory().getPath();
**。 - Paresh Mayani